有没有办法在 Spring MVC 中获取当前 session ,但不是通过请求。通常我们所做的是在 Action/Controller 类方法中获取请求。从这个请求中,我们通过 request.getSession() 获得 session 。但是有没有办法在没有这个请求对象的情况下获得这个 session 呢?
我的动机是,在一个实用程序类中,我需要访问一个在 session 中设置的值,并且该实用程序类方法正在从 Controller 类的 50 多个方法中访问。如果我必须从请求中获取 session ,那么我将需要更改所有这 50 个位置。这看起来很乏味。请提出替代方案。
最佳答案
我们总是可以在不传递 HttpServletRequest 的情况下从 Controller 空间中检索 HttpSession。
Spring 提供了监听器,将请求暴露给当前线程。可以引用RequestContextListener .
这个监听器应该在你的 web.xml 中注册
<listener>
<description>Servlet listener that exposes the request to the current thread</description>
<display-name>RequestContextListener</display-name>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
这就是您从 Session 获取详细信息的方法。
public final User getUser() {
RequestAttributes requestAttributes = RequestContextHolder
.currentRequestAttributes();
ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
HttpServletRequest request = attributes.getRequest();
HttpSession httpSession = request.getSession(true);
Object userObject = httpSession.getAttribute("WEB_USER");
if (userObject == null) {
return null;
}
User user = (User) userObject;
return user;
}
关于java - 如何在没有请求的情况下获取 Spring session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38051326/