表单验证错误后,Spring MVC(既不是BindingResult也不是bean名称的普通目标对象)

Mid*_*lue 2 java spring jsp spring-mvc

我遇到一个模型属性的问题,在表单验证后似乎"消失":

public class QuestionController {
    //...
    @RequestMapping(value="/get", method=RequestMethod.GET)
    public String prepareVoterBean(Model model, @RequestParam String voterID) {
        ...
        VoterBean questions = service.getQuestionBean(voterID);
        model.addAttribute("questions", questions);
        return "questionPage";
    }

    @RequestMapping(method=RequestMethod.POST)
    public String processSubmit(@Valid VoterBean questions, BindingResult result) {
        if (result.hasErrors()) {
            logger.info("QuestionController encountered form errors ");
            return "questionPage";
        }
        return "redirect:/ballot/get";
       }
Run Code Online (Sandbox Code Playgroud)

以下是questionPage.jsp,其中既没有BindingResult也没有bean名称('questions')的普通目标对象:

<form:form modelAttribute="questions" method="post">
    <fieldset>      
        <legend>Security Questions</legend>
        <p>
            <form:label for="birthDate" path="birthDate" cssErrorClass="error"> <fmt:message key="questions.birthDate"/>: </form:label></br>
            <form:input path="birthDate" /><form:errors path="birthDate"/>
        </p>
        //...
Run Code Online (Sandbox Code Playgroud)

使用HTTP get请求可以很好地呈现questionPage,但是当我提交表单wtith验证错误,从而触发processSubmit()返回到questionPage时,我有BindingResult错误.我很困惑我做错了什么,因为我问题bean必须在第一次返回时才可用于questionPage,但是然后突然页面在HTTP POST请求之后找不到bean并且验证错误.非常感谢您的帮助.谢谢.

Aff*_*ffe 6

如果你想让bean自动地回到地图上,你需要通过注释method参数告诉Spring使用地图中的bean作为绑定目标:

@RequestMapping(method=RequestMethod.POST)
public String processSubmit(@Valid @ModelAttribute("questions") VoterBean questions, BindingResult result) {
    if (result.hasErrors()) {
        logger.info("QuestionController encountered form errors ");
        return "questionPage";
    }
    return "redirect:/ballot/get";
   }
Run Code Online (Sandbox Code Playgroud)