Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a HttpSession in a ClientHttpRequestInterceptor in Spring MVC

I access my sessions in Spring MVC controllers simply with @Autowired like this:

@Autowired
private HttpSession session;

The problem is, I have now access the session within a ClientHttpRequestInterceptor.

I tried it with RequestContextHolder.getRequestAttributes() but the result is (sometimes - and this is a real problem) null. I tried it also with RequestContextHolder.currentRequestAttributes() but than the IllegalStateException is thrown with the following message:

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

The RequestContextListener is registered in web.xml.

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

The same problem when I inject the session in the ClientHttpRequestInterceptor directly.

@Autowired
private HttpSession session;

My question is: how can I access the current HttpSession in the ClientHttpRequestInterceptor?

Thanks!

like image 799
Robert Moszczynski Avatar asked Sep 15 '25 15:09

Robert Moszczynski


1 Answers

You can access the HttpSession by using the following in your ClientHttpRequestInterceptor:

public class CustomInterceptor implements ClientHttpRequestInterceptor {
        @Override
        public ClientHttpResponse intercept(HttpRequest request,
                                            byte[] body,
                                            ClientHttpRequestExecution execution) throws IOException {
            HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            // get the current session without creating a new one
            HttpSession httpSession = httpServletRequest.getSession(false);
            // get whatever session parameter you want
            String sessionParam = httpSession.getAttribute("parameter")
                                             .toString();
        }
    }
like image 123
Osama Sayed Avatar answered Sep 18 '25 06:09

Osama Sayed