Spring MVC 3 @ModelAttribute Annotation Example
Monday, April 18th, 2011
Background
So, I’m working on an existing Spring 3.x web project. This project heavily favours the use of annotations over XML configuration files. As I was trawling through the source code I noticed the “@ModelAttribute” annotation (which of course I had to look up!).
If the above background seems familiar that’s because it’s the same as for a previous Spring Annotation post I made (ed: this is in danger of turning into a mini-series)
Description
Most of the following is based upon the excellent Spring Documentation. I’ve simply lifted and rewritten the parts I require to serve as an “aide-mémoire”.
The @ModelAttribute annotation serves two purposes depending on how it is used:
At Method level
Use @ModelAttribute at the method level to provide reference data for the model. @ModelAttribute annotated methods are executed before the chosen @RequestMapping annotated handler method. They effectively pre-populate the implicit model with specific attributes, often loaded from a database. Such an attribute can then already be accessed through @ModelAttribute annotated handler method parameters in the chosen handler method, potentially with binding and validation applied to it.
In other words; a method annotated with @ModelAttribute will populate the specified “key” in the model. This happens BEFORE the @RequestMapping
At Method Parameter level
When you place @ModelAttribute on a method parameter, @ModelAttribute maps a model attribute to the specific, annotated method parameter. This is how the controller gets a reference to the object holding the data entered in the form.
Examples
Method Level
@Controller public class MyController { @ModelAttribute("productsList") public Collection<Product> populateProducts() { return this.productsService.getProducts(); } // @RequestMapping etc omitted for brevity }
So, in the above example, “productsList” in the Model is populated before the the @RequestMapping is performed.
Method parameter level
@Controller public class MyController { @RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("product") Product myProduct, BindingResult result, SessionStatus status) { new ProductValidator().validate(myProduct, result); if (result.hasErrors()) { return "productForm"; } else { this.productsService.saveProduct(myProduct); status.setComplete(); return "productSaved"; } } }
In the above example “myProduct” is populated with the corresponding value from the Model.
You can leave a response, or trackback from your own site.
Tags: annotations, java, spring
Posted in: Spring