Spring MVC Attributes

While developing a web application we have to take care of the scopes (session / request) of objects that are used to manipulate data. Spring MVC provides many ways to handle such data in various scopes using the different types of attributes. In the article we will focus mainly on 3 types of Spring MVC attributes.

Model Attributes

Model attributes can be declared using @ModelAttribute  annotation. This annotation is also used to define the command object used by the HTTP request and the form tags.
Model attributes are used in form handling; displaying of form data or updating the form data.

@ModelAttribute annotation can be used in following ways
In the below code the model can be accessed from the view with the key name as “testObject”

In the below code the model is passed from the view to the controller as parameter.

Also see Model Attributes in Details

Session Attributes

Session attributes in spring mvc can be defined using the @SessionAttributes annotation.
@SessionAttributes is used on a controller and it tells spring which model attributes need to be stored in the session.

These session attributes can be cleared from the session using the SessionStatus without having to end the entire session.

Also see Session Attributes in Details

Flash Attributes

Flash Attributes are useful when a user wants to display messages regarding a form submission or a error on form using data from the previous request used in form.
Normally when processing of a POST request is completed on the server, the request attributes are lost as the requested resource (view) will displayed to the user using a FORWARD/REDIRECT.

In the below code we are using the flash attribute to display a message using the data from the model attribute

Also see Flash Attributes in Details