我如何设置一个 session 对象,然后我可以通过使用 ${variable}
在我的任何 View 中使用它或 ${requestScope.variable}
为了能够使用 session ,我需要设置 <%@ page session="true" %>
?
最佳答案
如果您想在 View 中访问 session 变量,最简单的方法是:
${sessionScope.yourVariable}
见 Using Scope Objects了解更多信息。
如果您设置 <%@ page session="true">
然后 JSP 会将 session 范围和页面范围合并到一个命名空间中。然后你可以这样做:
${yourVariable}
你可以像这样在 mvc Controller 的 session 中加入一些东西:
@RequestMapping("/test")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request)
{
request.getSession().setAttribute("testVariable", "Test Values!!");
return "testJsp";
}
}
最后,@SessionAttribute 是针对特定用例的,它不会将变量放入 session 中以便任何人都可以访问它们:
Spring 的人们是这样描述@SessionAttribute 的功能的:
The @SessionAttributes works in the same way as the sessionForm of the SimpleFormController. It puts the command (or for the @SessionAttributes any object) in the session for the duration between the first and the last request (most of the time the initial GET and the final POST). After that the stuff is removed.
Each Controller has it's own ModelMap so something put as a @SessionAttributes in controller1 isn't available in controller2 and vice versa. For that to work you will have to put stuff on the session manually yourself.
关于java - 设置 session 变量spring mvc 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5938951/