I have been looking for a way to make form validation as easy and unobtrusive as possible in Spring MVC 3. I like the way spring can handle Bean Validation by passing @Valid to my model (that has been annotated with validator annotations) and using the result.hasErrors() method.
I am setting up my controller actions like this:
@RequestMapping(value = "/domainofexpertise", method = RequestMethod.PUT)
public String addDomainOfExpertise(@ModelAttribute("domainOfExpertise")
@Valid DomainOfExpertise domainOfExpertise, final BindingResult result) {
if (result.hasErrors()) {
return "/domainofexpertise/add";
} else {
domainOfExpertiseService.save(domainOfExpertise);
return "redirect:/admin/domainofexpertise/list";
}
}
Which works like a charm. Database exceptions (like trying to save something with a unique constraint on a field) will still get through. Is there any way to incorporate catching those exceptions in the validation process going on behind the scenes? This way of validating is very concise so I want to avoid having to manually catch them in my controller.
Any information on this?
Here is an example I use to convert PersistentExceptions to a friendlier message. It is a method that goes in the Controller. Will this work for you?