Spring 3.0设置并获取会话属性 [英] Spring 3.0 set and get session attribute
问题描述
我想从会话范围读取域对象(UserVO)。
I want to read a domain object (UserVO) from session scope.
我在名为WelcomeController的控制器中设置UserVO
I am setting the UserVO in a controller called WelcomeController
@Controller
@RequestMapping("/welcome.htm")
public class WelcomeController {
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(BindingResult result, SessionStatus status,HttpSession session){
User user = loginService.loginUser(loginCredentials);
session.setAttribute("user", user);
return "loginSuccess";
}
}
我能够在jsp页面中使用该对象< h1> $ {user.userDetails.firstName}< / h1>
I am able to use the object in jsp pages <h1>${user.userDetails.firstName}</h1>
但我无法从另一个Controller读取值,
But I am not able to read the value from another Controller,
我正在尝试读取会话属性,如下所示:
I am trying to read the session attribute as follows:
@Controller
public class InspectionTypeController {
@RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
public String addInspectionType(InspectionType inspectionType, HttpSession session)
{
User user = (User) session.getAttribute("user");
System.out.println("User: "+ user.getUserDetails().getFirstName);
}
}
推荐答案
您显示的代码应该工作 - HttpSession
在控制器之间共享,并且您使用相同的属性名称。因此,你没有向我们展示其他东西。
The code you've shown should work - the HttpSession
is shared between the controllers, and you're using the same attribute name. Thus something else is going wrong that you're not showing us.
然而,无论它是否有效,Spring提供了一种更优雅的方法来保存模型对象在会话中,使用 @SessionAttribute
注释(参见 docs )。
However, regardless of whether or not it works, Spring provides a more elegant approach to keeping your model objects in the session, using the @SessionAttribute
annotation (see docs).
例如(我还没有)测试了这个,但它给你的想法):
For example (I haven't tested this, but it gives you the idea):
@Controller
@RequestMapping("/welcome.htm")
@SessionAttributes({"user"})
public class WelcomeController {
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(ModelMap modelMap){
User user = loginService.loginUser(loginCredentials);
modelMap.addtAttribute(user);
return "loginSuccess";
}
}
然后
@Controller
@SessionAttributes({"user"})
public class InspectionTypeController {
@RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
public void addInspectionType(InspectionType inspectionType, @ModelAttribute User user) {
System.out.println("User: "+ user.getUserDetails().getFirstName);
}
}
但是,如果您的原始代码不起作用,然后这也不会起作用,因为你的会话有其他问题。
However, if your original code isn't working, then this won't work either, since something else is wrong with your session.
这篇关于Spring 3.0设置并获取会话属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!