bin*_*ary 14 java spring session-variables
我想从会话范围中读取域对象(UserVO).
我在名为WelcomeController的控制器中设置UserVO
@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";
}
}
Run Code Online (Sandbox Code Playgroud)
我能够在jsp页面中使用该对象 <h1>${user.userDetails.firstName}</h1>
但是我无法从另一个Controller中读取值,
我正在尝试读取session属性,如下所示:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
ska*_*man 40
您显示的代码应该起作用 - 在HttpSession控制器之间共享,并且您使用相同的属性名称.因此,你没有向我们展示其他错误.
但是,无论它是否有效,Spring都提供了一种更优雅的方法,使用@SessionAttribute注释将模型对象保留在会话中(请参阅文档).
例如(我没有测试过这个,但它给你的想法):
@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";
}
}
Run Code Online (Sandbox Code Playgroud)
然后
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果您的原始代码不起作用,那么这也不起作用,因为您的会话出现了其他问题.
小智 6
@SessionAttributes仅在特定处理程序的上下文中起作用,因此WelcomeController中的属性集仅在此控制器中可见.
| 归档时间: |
|
| 查看次数: |
97844 次 |
| 最近记录: |