11

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

它只返回字符串而不是对象。我想在尝试使用@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;
    }

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

4

1 回答 1

33

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

也不要忘记常见的新手陷阱:确保您的会话对象可序列化。

于 2013-07-18T12:08:04.717 回答