Found an interesting little gotcha at work last week, I was adding form validation to an annotated Spring controller, creating a custom Validator to do the work and wiring it in to the controller's method signature with the use of the BindingResult parameter (I just tacked it on the end of my existing parameters):
So basically it meant that my controller method should have been this:
Technorati Tags: Spring, Annotation, Validation, Level Up, Mark Lishman, Andrew Beacock
@RequestMapping(method=RequestMethod.POST, params="action=person") public String createPerson(@ModelAttribute("person") PersonForm person, ModelMap model, BindingResult result) { // code goes here... }This resulted in a slightly odd error message:
java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!I was a little confused by this message, it was indicating that I didn't have the form's model attribute declared before the BindingResult but I certainly have. After some google searching for this error message I found a website created by a colleague of mine (Mark Lishman) which had just the answer that I needed:
The BindingResult
parameter must be positioned directly after the corresponding model argument that is being validated.
Taken from the information tip box on the Level Up Spring MVC Form Validation page.So basically it meant that my controller method should have been this:
@RequestMapping(method=RequestMethod.POST, params="action=person") public String createPerson(@ModelAttribute("person") PersonForm person, BindingResult result, ModelMap model) { // code goes here... }Level Up is an excellent resource for people starting out with Spring, Hibernate & Oracle, check it all out at the Level Up website.
Technorati Tags: Spring, Annotation, Validation, Level Up, Mark Lishman, Andrew Beacock
Comments
Thanks vry much..
@RequestMapping(method = RequestMethod.GET)
public void setupForm(Model model, @ModelAttribute NameOfYourrCommandObject cmd, BindingResult errors, HttpServletRequest request, HttpSession session)
@RequestMapping(method = RequestMethod.GET)
public void setupForm(Model model, @ModelAttribute NameOfYourrCommandObject cmd, BindingResult errors, HttpServletRequest request, HttpSession session)
This was very very helpful!
Jorge