Reputation: 41
As Spring Specification said, @ModelAttribute will executed before the mapping handler and @SessionAttribute will keep the model attribute in session.
Consider below scenario: form bean is created after the controller is called and is set as session attribute as well. Next time MenuController is called, createForm() will be executed again and create another new form bean. My question is: will this latest created form bean be set as session attribute? and which form bean will be bind to the parameter in method bookList()?
Hope you guys can help. Thank you.
@Controller
@RequestMapping("/store")
@SessionAttribute("form")
public class MenuController {
@ModelAttribute("form")
public Form createForm() {
return new Form();
}
@RqeustMapping("/book")
public String bookList(@ModelAttribute("form") Form form){
//processing the form
}
}
Upvotes: 4
Views: 10596
Reputation: 21
The @SessionAttributes indicates that the "form" will be saved in the session. not meaning the "form" is retrieved from the session.
Upvotes: 2
Reputation: 3378
When the bookList
method is invoked for the first time in a given session, then method with @ModelAttribute('form)
is invoked, the returned value (Form object) is stored in HttpSession
and finally the bookList
method is invoked with the same Form object passed as an argument (obtained from session).
For the subsequent requests within the same HttpSession
, Spring retrieves the same Form object from the session and doesn't call the method with @ModelAttribute('form')
again till the end of the session.
After each end of the bookList
method invocation Spring stores updated version of Form object in HttpSession
.
If you are using Spring Boot 2.x you can debug DefaultSessionAttributeStore#retrieveAttribute method to understand this behaviour.
Upvotes: 5
Reputation: 130
Remember that your mapping is generalised. It will map both to a GET method and a POST method.
If your request mapping is a GET method,
The session attribute will hold the value of the @ModelAttribute("form") from the method createForm.
If an attribute form is returned from a POST request,
The session Attribute will override the @Model Attribute from the createForm method.
It is helpful to remember that the @ModelAttribute will execute before the mapping handler.
Upvotes: 1