What is @ModelAttribute in Spring MVC? What is @ModelAttribute in Spring MVC? java java

What is @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")@Beforepublic 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.


For my style, I always use @ModelAttribute to catch object from spring form jsp. for example, I design form on jsp page, that form exist with commandName

<form:form commandName="Book" action="" methon="post">      <form:input type="text" path="title"></form:input></form:form>

and I catch the object on controller with follow code

public String controllerPost(@ModelAttribute("Book") Book book)

and every field name of book must be match with path in sub-element of form