Does Spring MVC create a new object defined as a ModelAttribute attribute for each call?

I am working on a set of pages similar to a wizard, where the user must enter a bit of data in several views for the final view, which allows them to go back and forth before the final submission. I tried to use the same Bean defined as ModelAttribute for all views, basically just passing that Bean around, like a token in which each view adds its own small bit of data.

The problem is that Spring MVC creates a new Bean on invocation. My admittedly fuzzy understanding of the model was that it was like inserting something into a session, and this object would work until the session was completed. This does not seem to be the case.

So, I guess the first question is: where are the model attributes “live” and for how long? Is there a better example for implementing a wizard-matched interface using only Spring MVC (I am limited and cannot use Web Flow ... its not an approved tool where I work)?

+4
source share
2 answers

Using the model attribute as a bean is not recommended. This is useful for manipulating form data before it is stored in the database.

@ModelAttribute("formAttribute") is created when you specify it as a parameter in your method:

 public void getForm(@ModelAttribute("formAttribute") Form form) { } 

It is created before each method call, calling it contruct:

 @ModelAttribute("formAttribute") public Form getForm() { return new Form(); } 

If it is not specified in the method parameter, it does not exist.

You can add your @ModelAttribute to the session by specifying @SessionAttributes on your controller:

 @Controller @SessionAttributes("formAttribute") public HelloController 

Then it is initialized once when you first use it, and is destroyed when you destroy it, calling:

 public void finalStep(SessionStatus status) { status.setComplete(); } 

I think that with the @SessionAttributes combination it is relatively easy to create a magic stream.

+3
source

If the web stream is not an option, you can try:

Save the model attribute as a session attribute, this is achieved by adding the @SessionAttribute annotation to your controller:

 @Controller @SessionAttribute("myconversationModel") public class MyFlowController{ @RequestMapping public String myMethod(@ModelAttribute("myconversationModel") ConversationModel myConversationModel){ .... } } 

Then, when you think you're done with the stream, just accept the optional SessionStatus parameter and call sessionStatus.complete , this will destroy the attribute from the session

 @RequestMapping public String myFinalMethod(@ModelAttribute("myconversationModel") ConversationModel myConversationModel, SessionStatus sessionStatus){ sessionStatus.complete(); .... } 
+1
source

All Articles