In Spring MVC I have the following controller:
@RequestMapping(value="adminUsers", method = RequestMethod.POST)
public ModelAndView listAdminUsers(Person newPerson, HttpServletResponse response) throws Exception {
Person person = personService.findPerson(newPerson.getUsername());
if (person == null) {
// Set errorText = "Invalid Person";
// redisplay view
ModelAndView mav = new ModelAndView("adminUsersList");
return mav;
} else {
Roles roles = new Roles();
roles.setPersonCode(person.getPersonCode());
roles.setRoleType("ADMN");
rolesMapper.insert(roles);
return new ModelAndView("redirect:/admin/adminUsers.html");
}
}
With the view:
<form:form method="post" action="${action}" commandName="person" >
<form:label path="username">Add new administrator:</form:label>
<form:input path="username" size="20"/>
<form:errors path="username" />
<input type="submit" value="Submit Changes"/> </form:form>
How would I return an error back to the view, so it is displayed by the <form:errors path="username" /> tag?
This is simlar to How to return error status and validation errors from this Spring MVC controller? except I’m returning a webpage, not a REST object, so the answers there don’t apply.
I don’t want to use Validator because the above calls the database, it’s not simply a check for if username is not empty etc.
Thanks!
Add
BindingResultto your method signature. From there,bindingResult.rejectValue("username", "username.notvalid", "Username is not valid");