我试图让我的控制器重定向到带有自定义错误消息的页面:
@RequestMapping(method=RequestMethod.POST)
public String processSubmit(@Valid Voter voter, BindingResult result, HttpServletRequest request) {
if (result.hasErrors()) {
logger.info("RegisterController encountered form errors ");
return "registerPage";
}
if (service.isVoterRegistered(voter.getVoterID())) {
logger.info("VoterID exists");
request.setAttribute("firstName", voter.getFirstName());
request.setAttribute("lastName", voter.getLastName());
request.setAttribute("ssn", voter.getSsn());
return "forward:/question";
}else {
logger.info("RegisterController is redirecting because it voter info failed to authenticate");
//TODO: should re-direct to register page with error
return "redirect:registerPage";
}
}
}
<!-- registerPage.jsp -->
<div class="container">
<h1>
Voter Registration
</h1>
<div class="span-12 last">
<form:form modelAttribute="voter" method="post">
<fieldset>
<legend>Voter Fields</legend>
<p>
<form:label for="firstName" path="firstName" cssErrorClass="error">First Name : </form:label></br>
<form:input path="firstName" /><form:errors path="firstName"/>
</p>
<p>
<form:label for="lastName" path="lastName" cssErrorClass="error">Last Name : </form:label> </br>
<form:input path="lastName" /> <form:errors path="lastName" />
</p>
<p>
<form:label for="ssn" path="ssn" cssErrorClass="error">Social Security Number : </form:label> </br>
<form:input path="ssn" /> <form:errors path="ssn" />
</p>
<p>
<input type="submit"/>
</p>
</fieldset>
</form:form>
</div>
<hr>
</div>
在重定向到 register.jsp 页面时,我希望页面显示一条错误消息,说明选民未注册。我的问题是如何让 Controller 返回页面,就好像表单有验证错误一样(即 result.hasErrors() == true) 。
提前致谢