Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is @ModelAttribute in Spring MVC?

What is the purpose and usage of @ModelAttribute in Spring MVC?

like image 436
Mohammad Adnan Avatar asked Aug 06 '10 11:08

Mohammad Adnan


People also ask

What is @ModelAttribute annotation in Spring MVC?

One of the most important Spring MVC annotations is the @ModelAttribute annotation. @ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view.

Can we use @ModelAttribute as a method argument?

As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments.

What is the difference between @ModelAttribute and @RequestBody?

@ModelAttribute is used for binding data from request param (in key value pairs), but @RequestBody is used for binding data from whole body of the request like POST,PUT.. request types which contains other format like json, xml.

What is a model attribute?

Model attributes are the data representations used internally by the model. Data attributes and model attributes can be the same. For example, a column called SIZE , with values S , M , and L , are attributes used by an algorithm to build a model.


1 Answers

@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".

like image 91
fasseg Avatar answered Sep 27 '22 22:09

fasseg