Friday, April 29, 2011

Upgrading to Spring MVC 2.5

I was trying to get familiarised with Spring MVC 2.5.I've used MVC 2.0 in the past and was counting to levarage on the experience.Gettings hands on I realised that 2.5 is a lot different from 2.0.The following are the major differences based on my understanding

Controllers:
Spring 2.5 has introduced Annotation based Controllers.Apart from the native controllers like AbstractController, SimpleFormController or MultiActionController, the DispatcherServlet can now handle any kind of action type.The controllers need not extend or implement MVC related classes or interface.A simple java class can serve as a controller by just adding the @Controller sterotype.

The annotated controllers are identified by specifying the context:component-scan in application context file.This specifies the package of the any annotated components that should be searched.

The methods that specify the mapping should be annotated with the @RequestMapping contruct .This maps the web request and specifies the type of method.The handler method signature are flexible and within a controller each mapping method can have different signature.The mapping methods allows to return nothing (void), a String representing a view, or just a model.By convention, if method does not explicitly return a view, the view name is defined by converting the mapped URL into a view name.

@ModelAttribute:
The methods marked with @ModelAttribute are invoked before every request.This can be used prepopulate the data required by the form.The functionality is similiar to the FormBackingObject in SimpleFormController.A controller can have any number of ModelAttribute methods.In most cases one method to populate the required data should suffice.


Validation and Binding Errors:
In Spring 2.0,injecting the validator bean would handle the Validation.But in 2.5,the validator needs to be injected and should be invoked manually.The BindingResult can be used to store the request data binding errors .If a method uses multiple objects a separate BindingResult instance can be defined for each object

Property Editor:
The Property editor can be registered using the method annotated with @InitBinder contruct.This is similiar to the initBinder() method .

The sample code has a simple form that has option in English/French to enter the data.The source code can be downloaded here.