Spring MVC form not returning value from dropdown

2019-08-08 21:38发布

I am an old servlet/html guy. I know this should be so straight forward, but I am unable to find an example of what I am trying to do. Perhaps my approach is wrong, but would appreciate some advice.

I am able to load a dropdown list using Spring form tag with a List<> of keys and values I have retrieved from a table, but when the form is submitted, I get an EMPTY List<> (size=0). I am able to retrieve the answer (input=text) from the form.

My Contoller:

    @RequestMapping(value = "/getQuestions", method = RequestMethod.GET)
public ModelAndView getQuestionsPage() {
    List<Question> questionsList = questionDAO.getAll();
    return new ModelAndView("questions", "questionsList", questionsList);
}

    @RequestMapping(method = RequestMethod.POST)
public ModelAndView processForm(@ModelAttribute("answer1") String answer1, @ModelAttribute("questionsList") java.util.ArrayList question) {
    ModelAndView model = new ModelAndView("home");
    return model;
}

Form section of the jsp:

<form action="questions" method="post" modelAttribute="questionsList">

<table>
    <tr>
        <td>Questions :</td>
        <td><form:select path="questionsList">
            <form:option value="0" label="Select" />
            <form:options items="${questionsList}" itemValue="id" itemLabel="question" />
            </form:select>
        </td>
    </tr>
    <tr>
        <td>Answer :</td>
        <td><input type="text" name="answer1"></td>
    <tr>
        <td><input type="submit" /></td>
    </tr>   
</table>    

I am thinking it may have something to do with the ??

Any help would be greatly appreciated!

1条回答
女痞
2楼-- · 2019-08-08 22:30

You are missing the name attribute on the form:select. For it to work with @ModelAttribute("questionsList") it would have to be something like:

<form:select path="questionsList" name="questionsList">

Although I truly discourage this, since it causes a lot of confusion with the path attribute, which has a totally different purpose.

Furthermore, your post data will only contain the selected value associated with the select name (ex: questionsList:1), so setting this to a list doesn't make that much sense.

You could try it like this:

JSP:

<form:select path="questionsList" name="questionId">

Controller:

public ModelAndView processForm(@ModelAttribute("answer1") String answer1, @ModelAttribute("questionId") Integer questionId) {
查看更多
登录 后发表回答