What is @ModelAttribute in Spring MVC?
What is the purpose and usage of @ModelAttribute
in Spring MVC?
@ModelAttribute
refers to a property of the Model object (the M in MVC ;)
so let's say we have a form with a form backing object that is called "Person"
Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute
annotation:
public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}
On the other hand the annotation is used to define objects which should be part of a Model. So if you want to have a Person object referenced in the Model you can use the following method:
@ModelAttribute("person")
public Person getPerson(){
return new Person();
}
This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.
See "Using @ModelAttribute".
I know this is an old thread, but I thought I throw my hat in the ring and see if I can muddy the water a little bit more :)
I found my initial struggle to understand @ModelAttribute
was a result of Spring's decision to combine several annotations into one. It became clearer once I split it into several smaller annotations:
For parameter annotations, think of @ModelAttribute
as the equivalent of @Autowired + @Qualifier
i.e. it tries to retrieve a bean with the given name from the Spring managed model. If the named bean is not found, instead of throwing an error or returning null
, it implicitly takes on the role of @Bean
i.e. Create a new instance using the default constructor and add the bean to the model.
For method annotations, think of @ModelAttribute
as the equivalent of @Bean + @Before
, i.e. it puts the bean constructed by user's code in the model and it's always called before a request handling method.
Figuratively, I see @ModelAttribute
as the following (please don't take it literally!!):
@Bean("person")
@Before
public Person createPerson(){
return new Person();
}
@RequestMapping(...)
public xxx handlePersonRequest( (@Autowired @Qualifier("person") | @Bean("person")) Person person, xxx){
...
}
As you can see, Spring made the right decision to make @ModelAttribute
an all-encompassing annotation; no one wants to see an annotation smorgasbord.