@SessionAttribute : When is the model initialized?

2019-02-11 06:49发布

问题:

When I want a model in Session scope in Spring 3, I use the foll. annotation in a Controller:-

    @SessionAttribute("myModel");

However, this is just the declaration of myModel. At which point does it gets initialized so that I use it in a View. And how will Spring know the class-type of this model?

Can someone explain this with example?

回答1:

@SessionAttribute works as follows:

  • @SessionAttribute is initialized when you put the corresponding attribute into model (either explicitly or using @ModelAttribute-annotated method).

  • @SessionAttribute is updated by the data from HTTP parameters when controller method with the corresponding model attribute in its signature is invoked.

  • @SessionAttributes are cleared when you call setComplete() on SessionStatus object passed into controller method as an argument.

Example:

@SessionAttribute("myModel")
@Controller
public class MyController {
    @RequestMapping(...)
    public String displayForm(@RequestParam("id") long id, ModelMap model) {
        MyModel m = findById(id);
        model.put("myModel", m); // Initialized
        return ...;
    }

    @RequestMapping(...)    
    public String submitForm(@ModelAttribute("myModel") @Valid MyModel m,
        BindingResult errors, SessionStatus status) {
        if (errors.hasErrors()) {
            // Will render a view with updated MyModel
            return ...;
        } else {
            status.setComplete(); // MyModel is removed from the session
            save(m);
            return ...;
        }

    }
}


回答2:

You can annotate methods with @ModelAttribute, if the attribute name is the same as specified in the the @SessionAttribute annotation then the attribute will be stored in the session. Here is a complete example :

@Controller   
@RequestMapping(value = "/test.htm") 
@SessionAttributes("myModel")
public class DeleteNewsFormController {

    // Add you model object to the session here
    @ModelAttribute("myModel")
    public String getResultSet() {
        return "Hello";
    }

    //retreive objects from the session
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody testMethod(@ModelAttribute("resultSet") String test, Model model) {