Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain session in spring without request?

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?

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.

like image 265
romil gaurav Avatar asked Mar 04 '26 08:03

romil gaurav


1 Answers

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

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

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>

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;
}
like image 68
Mihir Gohel Avatar answered Mar 05 '26 20:03

Mihir Gohel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!