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”
1 2 3 4 |
@ModelAttribute("testObject") public TestObject getTestObject() { return new TestObject(); } |
In the below code the model is passed from the view to the controller as parameter.
1 2 3 4 5 |
@RequestMapping(value = "/process", method = RequestMethod.GET) public ModelAndView processRequest(@ModelAttribute("testObject") TestObject testObject) { //Do processing on testObject; return new ModelAndView("myView"); } |
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.
1 2 3 4 5 |
@Controller @SessionAttributes("testObject") public class TestController { ...... } |
These session attributes can be cleared from the session using the SessionStatus without having to end the entire session.
1 2 3 4 5 |
@RequestMapping(value = "/clearSessionAttributes", method = RequestMethod.GET) public ModelAndView processRequest(SessionStatus sessionStatus) { sessionStatus.setComplete(); return new ModelAndView("myView"); } |
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
1 2 3 4 5 6 7 8 9 |
@RequestMapping(value = "/processRequest", method = RequestMethod.GET) public String processRequest(@ModelAttribute("userDetails") UserDetails userDetails, final RedirectAttributes redirectAttribute) { // process the request and submit data from userDetails redirectAttribute.addFlashAttribute("successMessage", "User Details updated for user :: " + userDetails.getuserName()); return "redirect:new_request"; } |
Also see Flash Attributes in Details