如何在没有请求的情况下获得春季会议

如何在没有请求的情况下获得春季会议

本文介绍了如何在没有请求的情况下获得春季会议?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to get current session in Spring MVC, but not by request. Typically what we do is we get request in Action/Controller class methods. From this request, we get session by request.getSession(). But is there a way to get this session without this request object?

我的动机是,在一个实用程序类中,我需要访问一个在会话中设置的值,并且这个实用程序类方法可以从控制器类的 50 多个方法中访问.如果我必须从请求中获取会话,那么我需要更改所有这 50 个位置.这看起来很乏味.请提出替代方案.

My motive is that in one utility class I need to access a value that is set in session and this utility class method is getting accessed from more than 50 methods of Controller classes. If I have to get session from request then I would need to change all these 50 places. This looks quite tedious. Please suggest an alternative.

推荐答案

我们总是可以在不传递 HttpServletRequest 的情况下从 Controller 空间中检索 HttpSession.

We can always retrive HttpSession out of Controller space without passing HttpServletRequest.

Spring 提供了将请求暴露给当前线程的监听器.您可以参考 RequestContextListener.

Spring provides listener that exposes the request to the current thread. You may refer RequestContextListener.

这个监听器应该在你的 web.xml 中注册

This listener should be registered in your 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 获取详细信息的方式.

and this is how you can get details from 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;
}

这篇关于如何在没有请求的情况下获得春季会议?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:59