Reputation: 5141
I am trying to make my Controller to redirect to a page with a custom error message:
@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>
On redirecting to register.jsp page, I want the page to display an error message, saying that the voter is not registered. My question is how to get Controller to return to a page as if the form had a validation error (i.e result.hasErrors() == true) .
Thanks in advance
Upvotes: 2
Views: 9439
Reputation: 1138
There's something wrong in your controller method. It would be better way to call getAllErrors()
method from result than the getFieldErrors()
. Of course if the result is BindingResult
type . Like this:
model.addAttribute("errors", result.getAllErrors());
Upvotes: 3
Reputation: 1786
You can add the following section in your 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>
Here c
is nothing but this--
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Also you need to pass the errors into the model and view like this inside the if block in your controller method--
model.addAttribute("errors",result.getFieldErrors());
error
class in the DIV is nothing but my custom css to display as a red block--
.error{
color: red;
border:2px solid red;
padding:10px;
}
You can also have a look at this
Hope my answer has helped you..
Upvotes: 6