简体   繁体   English

设置会话变量spring mvc 3

[英]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} 如何使用${variable}${requestScope.variable}设置我可以在任何视图中使用的会话对象

To be able to use sessions do I need to set <%@ page session="true" %> ? 为了能够使用会话,我需要设置<%@ 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. 如果设置<%@ page session="true">则JSP会将会话范围和页面范围合并到单个命名空间中。 Then you can do: 然后你可以这样做:

${yourVariable}

You can put something into the session in a mvc controller like this: 您可以在mvc控制器中将某些内容放入会话中,如下所示:

@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: 最后,@ SessionAttribute用于特定用例,并且不会将变量放入会话中,以便任何人都可以访问它们:

Here is how the spring folks describe the functionality of @SessionAttribute: 以下是春天人们如何描述@SessionAttribute的功能:

The @SessionAttributes works in the same way as the sessionForm of the SimpleFormController. @SessionAttributes的工作方式与SimpleFormController的sessionForm相同。 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). 它将命令(或@SessionAttributes任何对象)放在会话中,持续时间为第一个和最后一个请求(大多数时间是初始GET和最终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. 每个Controller都有自己的ModelMap,因此在controller1中作为@SessionAttributes放置的内容在controller2中不可用,反之亦然。 For that to work you will have to put stuff on the session manually yourself. 为此,你必须自己手动将东西放在会话上。

Use the SessionAttributes Annotation. 使用SessionAttributes Annotation。 Check it out at the spring documentation here 请在弹簧文档中查看

You can also manually add and remove variables from session with the DefaultSessionAttributeStore api 您还可以使用DefaultSessionAttributeStore api手动添加和删除会话中的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM