繁体   English   中英

如何在Spring会话中存储每个用户数据?

[英]How can I store per user data in Spring session?

我想为每个登录的用户存储,他的身份在Spring会话中。 我做的是:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
.getRequestAttributes()).getRequest();
    HttpSession session = request.getSession(true);

    session.getServletContext().setAttribute("userId", userId); 

当我需要id时,我正在做

 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();  
 HttpSession session = request.getSession();
 Long userId = (Long) session.getServletContext().getAttribute("userId");

第一个用户登录,获取会话ID即可。

第二个用户登录,会话ID被覆盖(我看到因为第一个用户的每个下一个操作,获取第二个用户的用户ID)

实现这一点的正确方法是什么,显然我不能正确理解会话?

感谢所有的建议

您将该属性存储在ServletContext ,该文件在同一Web应用程序的所有会话之间共享

您应该将属性存储在HttpSession本身中:

session.setAttribute("userId", userId);

然后检索它:

Long userId = (Long) session.getAttribute("userId");

你没有在这里使用HttpSession ,你正在使用ServletContext ,顾名思义,这是一个单例。

session.setAttribute("userId", userId);

Long userId = (Long) session.getAttribute("userId");

我更喜欢在HttpSession中保存sessionBean对象...您可以使用要保留在会话中的数据创建bean

session.setAttribute( “sessionData”,一个sessionBean);

暂无
暂无

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

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