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!
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With