Thursday, December 23, 2010

Spring MVC ModelAttribute and BindingResult

The Problem:

I am using Spring 3 MVC and I encountered the following error upon form submission:

org.springframework.validation.BindException type mismatch

In my controller I defined the following 2 model attributes:

        model.addAttribute("gene",gene);        
        model.addAttribute("renameAllele", ra);

Upon form submission, I wanted to bind the ModelAttribute to my method arguments as follows:

    @RequestMapping(value="/renameAllele/submit", method=RequestMethod.POST)
    public String submit(@ModelAttribute("renameAllele") @Valid final RenameAllele ra, BindingResult alleleBindingResult, 
            @ModelAttribute("gene") RenameGene gene, SessionStatus status ) {

This method signature didn't work because for every ModelAttribute added, we need to have a corresponding BindingResult argument as well. As you can see above, the ModelAttribute("gene") did not have a corresponding BindingResult.

Solution

To get it working, I changed the method signature as follows:

    @RequestMapping(value="/renameAllele/submit", method=RequestMethod.POST)
    public String submit(@ModelAttribute("renameAllele") @Valid final RenameAllele ra, BindingResult alleleBindingResult, 
            @ModelAttribute("gene") RenameGene gene, BindingResult geneBindingResult, 
            SessionStatus status ) {

I figured this out by reading the spring reference documentation. Here is a quote taken from their site:
"The Errors or BindingResult parameters have to follow the model object that is being bound immediately as the method signature might have more that one model object and Spring will create a separate BindingResult instance for each of them so the following sample won't work:"
Reference: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html

1 comment:

  1. Thank you - I just spent ~2hours trying to find an error and didn't think of such a simple thing. Thx :)

    ReplyDelete