What is the purpose and usage of @ModelAttribute
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.
As described in the Spring MVC documentation - the @ModelAttribute annotation can be used on methods or on method arguments.
@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.
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.
@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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With