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


问题内容

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

它仅返回字符串,而不返回对象。我想在尝试将@SessionAttribute设置为会话中的对象时使用@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;
    }

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


问题答案:

@SessionAttributes 注释在类级别用于:

  1. 标记模型属性应在 执行处理程序方法后* 保留到HttpSession *
  2. 在执行处理程序方法之前 ,使用HttpSession中先前保存的对象填充模型 -如果存在的话

因此,您可以@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陷阱:请确保将会话对象设置为可序列化。