Springmvc如何发送多维单选按钮数组到控制器



我试图从反馈,但我不能得到任何关于如何发送多维int数组从表单到控制器的例子。

pic: http://oi58.tinypic.com/p1z10.jpg

控制器

@RequestMapping(value = "/submitfeedback", method = RequestMethod.POST)
public String postsubmitfeedback(@ModelAttribute("answer") @RequestParam("email") String email,
        @RequestParam("feedback_id") Integer feedback_id, @RequestParam(value="myanswer[]") int [] myanswer,  Answer answer,
        Locale locale) {
        for(int i=0; i<myanswer.length;i++) {
            System.out.println(myanswer[i]);
        }
    return "submitfeedback";
}

Jsp表单

<form:form commandName="feedback">
<c:forEach items="${questionList}" var="question">
<c:set var="counter" value="${counter + 1}"/>
<tr>
    <td>${counter}</td>
    <td>${question.question}</td>
    <td><input type="radio" name="myanswer[${count}]" id="radio" value="1" /> 1</td>
    <td><input type="radio" name="myanswer[${count}]" id="radio" value="2" /> 2</td>
    <td><input type="radio" name="myanswer[${count}]" id="radio" value="3" /> 3</td>
    <td><input type="radio" name="myanswer[${count}]" id="radio" value="4" /> 4</td>
    <td><input type="radio" name="myanswer[${count}]" id="radio" value="5" /> 5</td>
</tr>
<c:set var="count" value="${count+1}"/>
</c:forEach>
</form:form>

首先,我强烈建议您将参数封装在对象中。

class FeedbackForm {
   private String email;
   private Integer feedbackId;
   private Integer answer;
   /** Getters and setters. */
}

html表单输入的名称应该与字段名称匹配。

其次,你有一个单选按钮控件,我怀疑你最终会得到一个整数数组,因为你只能一直选择一个单选按钮。在上面的bean中,我将其更正为一个答案。单选按钮有点奇怪,因为它们在表单中有多个输入。您可能应该有这样的内容:

<input type="radio" name="answer" value="1" onClick="changeMyHiddenField()" />1
<input type="radio" name="answer" value="2" onClick="changeMyHiddenField()" />2
<input type="radio" name="answer" value="3" onClick="changeMyHiddenField()" />3
<form {...}> <input id="myHiddenField" type="hidden" name="answer" /> </form>

第三,您没有对客户端的输入进行验证。您应该利用Spring的bean验证。

@Min(value = 1, message = "Min is 1.")
@Max(value = 5, message = "Max is 5.")
private Integer answer;
最后,你的方法签名应该像这样:
public String postFeedback(@ModelAttribute @Valid FeedbackForm form, HttpServletRequest request, Locale locale);

相关内容

  • 没有找到相关文章

最新更新