spring如何在没有请求的情况下获取会话?


问题内容

有没有一种方法可以在Spring MVC中获取当前会话,但不能通过请求获取。通常,我们要做的是在Action /
Controller类方法中获得请求。从此请求,我们通过request.getSession()获得会话。但是有没有一种方法可以在没有此请求对象的情况下获得此会话?

我的动机是,在一个实用程序类中,我需要访问一个在会话中设置的值,并且该实用程序类方法正从50多种Controller类方法中进行访问。如果我必须从请求中获取会话,则需要更改所有这50个位置。这看起来很乏味。请提出一个替代方案。


问题答案:

我们总是可以在不传递HttpServletRequest的情况下从控制器空间中检索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;
}