Spring @SessionAttribute how to retrieve the session object in same controller

前端 未结 1 1983
有刺的猬
有刺的猬 2020-12-25 08:21

I am using Spring 3.2.0 MVC. In that I have to store one object to session. Currently I am using HttpSession set and get attribute to store and retrieve the value.

I

相关标签:
1条回答
  • 2020-12-25 09:11

    @SessionAttributes annotation are used on the class level to :

    1. Mark a model attribute should be persisted to HttpSession after handler methods are executed
    2. Populate your model with previously saved object from HttpSession before handler methods are executed -- if one do exists

    So you can use it alongside your @ModelAttribute annotation like in this example:

    @Controller
    @RequestMapping("/counter")
    @SessionAttributes("mycounter")
    public class CounterController {
    
      // Checks if there's a model attribute 'mycounter', if not create a new one.
      // Since 'mycounter' is labelled as session attribute it will be persisted to
      // HttpSession
      @RequestMapping(method = GET)
      public String get(Model model) {
        if(!model.containsAttribute("mycounter")) {
          model.addAttribute("mycounter", new MyCounter(0));
        }
        return "counter";
      }
    
      // Obtain 'mycounter' object for this user's session and increment it
      @RequestMapping(method = POST)
      public String post(@ModelAttribute("mycounter") MyCounter myCounter) {
        myCounter.increment();
        return "redirect:/counter";
      }
    }
    

    Also don't forget common noobie pitfall: make sure you make your session objects Serializable.

    0 讨论(0)
提交回复
热议问题