Spring MVC Validation BindingResult

A quick note about using the BindingResult to detect and report errors in a form. One gotcha that got me was the need to set a name on the @ModelAttribute in order to properly relate the form:form commandName and the validation object. Essentially, if you don’t set a name then @ModelAttribute will get the command name from the name of the argument, and BindingResult will get the command name from the type of the argument, meaning that when you go to use form:errors nothing will be displayed.

ie, this didn’t work because @ModelAttribute was using “myObject”, while BindingResult was using “objectClass”:

public String saveObject(ModelMap model,
            @Valid @ModelAttribute ObjectClass myObject, BindingResult result)

This did work:

public String saveObject(ModelMap model,
            @Valid @ModelAttribute("myObject") ObjectClass myObject, BindingResult result)

At the JSP end things looked like this, where “attr” is an attribute that is being checked:

<form:form commandName="myObject">
...
<form:errors path="attr" />
...
</form:form>

 

This entry was posted in java, Spring. Bookmark the permalink.

One Response to Spring MVC Validation BindingResult

  1. Krishna says:

    Hi,

    I have tried the above procedure but not able to show message on JSP page
    Can you please give me some more details.
    Thanks

Leave a Reply