Spring MVC Model Attributes

Spring MVC Model Attributes are used to bind data either as method parameter or its return value. It is also very commonly used to bind/show data on forms. @ModelAttribute is used to describe a Model Attribute. Lets see the various ways a Model Attribute is used.

@ModelAttribute as a method param

@ModelAttribute as a method param is normally used to access the details on a form.
When we use a @ModelAttribute as a method param, the framework tries to retrieve it from the Model.
If it is not present in the Model, then the param should be instantiated and added to model before using it.

On a form when we pass the instantiated Model Attribute, we need to add the exact matching fields that are present in the Model Attribute object.
This is data binding and is very useful in mapping each form element to the fields in Model Attribute.

We have a EmployeeDetails Object. It has fullName and department fields.

To use the EmployeeDetails as a Model Attribute in a form, we need to first instantiate it and add to the Model.

Now you can the EmployeeDetails object in the form and then use that back as a Model Attribute

@ModelAttribute on a method

Using @ModelAttribute on a method means you are adding one or more model attributes. You can do it in 2 ways
1. Returning Model Attribute

2. Adding more than one model attribute using Model

I hope this post helped you in understanding the Spring MVC Model Attributes.


Spring MVC Docs

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn