Omgo's Blog

October 24, 2009

Spring MVC 3.x @Valid (JSR 303) Annotation Support

Filed under: Spring — Tags: , , , — aswin @ 1:53 am

The spring controllers have become really snazzy with annotation based controllers the 2.5 release and it continues to evolve in that direction.  The  old approach (extending framework classes such as SimpleFormController)  is deprecated as of  Spring 3.x and the new design seems to be going in the right direction .  There are of course certain disciplines one has to adopt to make these new styled controllers maintainable , otherwise this flexibility would be very reason for troubles.  This blog has a very good suggestions on designing controllers with Spring MVC annotations using Spring 2.5.  As mentioned in the blog , in Spring 2.5 one had to explicitly call the validate on the form objects, but Spring 3.x version adds the support to annotate the RequetMapping method argument with a @Valid annotation so you don’t have to explicitly validate your form/command objects.  So you would do the following to get the framework validate the command object for you

import javax.validation.Valid;
......

@RequestMapping(method=RequestMethod.POST)
	public String postNewUser(@Valid User user, BindingResult results, ModelMap mmap)  {

             if (results.hasErrors()) {
                   return formView(mmap);
             }
             return successView(mmap);
        }

The formView() and successView() methods from this example are local methods that are used to populate the model values and also to return the view names to forward to.  This style would be really useful to deal with certain issues when not using @ModelAttribute annotation to populate the  model. I will write about this in a later post.

Of course, for this to work you need to have the following in your spring applicationcontext.xml.


<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<!-- Configures Spring MVC DataBinder instances -->
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
</property>
</bean>

<!-- Creates the JSR-303 Validator -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

The official spring documentation reference that explains this in detail is here. For this to work you would need a JSR 303 validator framework in the classpath and using maven this is as simple as adding the following in your pom.xml.   This  post has lot more information on the JSR 303 itself.

<dependency>
<groupId>org.hibernate</groupId></pre>
<artifactId>hibernate-validator</artifactId>
<version>4.0.0.GA</version>
</dependency>
<pre>

References

Validation Annotations Reference (including Hibernate custom ones)

Spring documentation on validaton

Advertisements

Blog at WordPress.com.