Spring MVC:如何重定向到有错误的页面?
问题内容:
我试图使我的控制器重定向到带有自定义错误消息的页面:
@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)。
提前致谢
问题答案:
您可以在jsp中添加以下部分-
<c:choose>
<c:when test="${not empty errors}">
<div class="error">
<c:forEach items="${errors}" var="err">
${err.defaultMessage}
<br/>
</c:forEach>
</div>
</c:when>
</c:choose>
这c
不过是this–
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
另外,您还需要将错误传递到模型中,并在控制器方法的if块中进行如下查看:
model.addAttribute("errors",result.getFieldErrors());
error
DIV中的 class 只是我的自定义CSS,显示为红色块-
.error{
color: red;
border:2px solid red;
padding:10px;
}
您也可以看看这个
希望我的回答对您有所帮助。