Spring @SessionAttribute如何在同一控制器中检索会话对象 [英] Spring @SessionAttribute how to retrieve the session object in same controller
问题描述
我正在使用Spring 3.2.0 MVC.在这种情况下,我必须将一个对象存储到会话. 目前,我正在使用HttpSession的set和get属性来存储和检索值.
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.
它仅返回String而不是Object.我想在尝试将@SessionAttribute设置为会话中的对象时使用@SessionAttribute,但是我无法检索会话对象
It returns only the String not Object. I want to use @SessionAttribute when I tried it sets the object in session but I could not retrieve the session object
@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;
}
这两种方法都在同一控制器中.我将如何使用它来检索对象?
Both methods are in same controller. How would I use this to retrieve the object?
推荐答案
@SessionAttributes
注释在类级别用于:
- 标记模型属性应在执行处理程序方法后持久保存到HttpSession
- 在执行处理程序方法之前,使用HttpSession中先前保存的对象填充模型-如果确实存在
- Mark a model attribute should be persisted to HttpSession after handler methods are executed
- Populate your model with previously saved object from HttpSession before handler methods are executed -- if one do exists
因此,您可以将其与@ModelAttribute
注释一起使用,例如以下示例:
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";
}
}
也不要忘记常见的noobie陷阱:请确保将会话对象设置为可序列化.
Also don't forget common noobie pitfall: make sure you make your session objects Serializable.
这篇关于Spring @SessionAttribute如何在同一控制器中检索会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!