Set session variable spring mvc 3
How can I set a session object which I can use then in any of my views by using ${variable}
or ${requestScope.variable}
To be able to use sessions do I need to set <%@ page session="开发者_如何学编程true" %>
?
If you want to access a session variable in your view the easiest way to do it is :
${sessionScope.yourVariable}
See the Using Scope Objects for more info.
If you set <%@ page session="true">
then the JSP will merge the session scope and at the page scope into a single namespace. Then you can do:
${yourVariable}
You can put something into the session in a mvc controller like this:
@RequestMapping("/test")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request)
{
request.getSession().setAttribute("testVariable", "Test Values!!");
return "testJsp";
}
}
Finally, the @SessionAttribute is meant for a specifc use case, and doesn't put variables into the session so that anyone can access them:
Here is how the spring folks describe the functionality of @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.
Use the SessionAttributes Annotation. Check it out at the spring documentation here
You can also manually add and remove variables from session with the DefaultSessionAttributeStore api
精彩评论