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

我使用的是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; } 

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

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

  1. 在执行处理程序方法后,应将标记属性标记为HttpSession
  2. 在执行处理程序方法之前,使用来自HttpSession的先前保存的对象填充模型– 如果存在的话

因此,您可以将其与@ModelAttribute注释一起@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陷阱:确保使会话对象可序列化。