Spring @SessionAttribute如何在同一个控制器中检索会话对象

时间:2013-07-18 11:49:11

标签: java spring spring-mvc

我正在使用Spring 3.2.0 MVC。在那里我必须将一个对象存储到会话中。 目前我正在使用HttpSession set和get属性来存储和检索值。

它只返回String而不是Object。我想在我尝试使用@SessionAttribute时在会话中设置对象但我无法检索会话对象

 @RequestMapping(value = "/sample-login", method = RequestMethod.POST)
    public String getLoginClient(HttpServletRequest request,ModelMap modelMap) {
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        User user = sample.createClient(userName, password);
        modelMap.addAttribute("userObject", user);
        return "user";
    }


     @RequestMapping(value = "/user-byName", method = RequestMethod.GET)
    public
    @ResponseBody
    String getUserByName(HttpServletRequest request,@ModelAttribute User user) {

        String fas= user.toString();
        return fas;
    }

两种方法都在同一个控制器中。我如何使用它来检索对象?

1 个答案:

答案 0 :(得分:29)

@SessionAttributes注释在类级别上用于:

  1. 在执行处理程序方法后,应将模型属性标记为HttpSession
  2. 在执行处理程序方法之前,使用HttpSession 中先前保存的对象填充模型 - 如果存在,
  3. 因此,您可以将其与@ModelAttribute注释一起使用,如下例所示:

    @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";
      }
    }
    

    另外,不要忘记常见的noobie陷阱:确保你的会话对象可以序列化。