Spring MVC表单未从下拉列表中返回值 [英] Spring MVC form not returning value from dropdown list

查看:53
本文介绍了Spring MVC表单未从下拉列表中返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是servlet/html的老家伙.我知道这应该很简单,但是我找不到我想做的事的例子.也许我的方法是错误的,但希望您能提供一些建议.

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.

我能够使用Spring表单标签加载下拉列表,其中包含我从表中检索到的键和值的列表<>>,但是提交表单后,我得到了一个EMPTY List<>(size = 0).我可以从表单中检索答案(input = text).

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.

我的Contoller:

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;
}

jsp的Form部分:

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>    

我认为这可能与??

任何帮助将不胜感激!

推荐答案

您缺少 form:select 上的 name 属性.为了与 @ModelAttribute("questionsList")一起使用,它必须类似于:

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">

尽管我确实不鼓励这样做,因为它与path属性造成了很多混淆,而path属性的用途却完全不同.

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

此外,您的帖子数据将仅包含与选择名称相关联的所选值(例如:questionsList:1),因此将其设置为列表没有太大意义.

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.

您可以这样尝试:

JSP:

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

控制器:

public ModelAndView processForm(@ModelAttribute("answer1") String answer1, @ModelAttribute("questionId") Integer questionId) {

这篇关于Spring MVC表单未从下拉列表中返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆