Access to HttpSession outside the source stream

I am using Spring 3. When the controller receives requests, it transfers control to someMethod() , annotated with @Async in the Service bean, and then returns. When I access the someMethod() HttpSession object, I get this exception

 java.lang.IllegalStateException: 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. 

How can i solve this?

+4
source share
1 answer

The HttpSession object itself can be used in multiple threads (but not thread-safe, and therefore must be synchronized). However, Spring does extra magic, for example. when you have session -scoped beans. Namely, it uses ThreadLocal from below to bind the current session to the thread.

I don't know what your exact scenario is, but apparently Spring is trying to extract the HttpSession from this ThreadLocal while you are in another thread that is obviously not working.

The solution is simple - extract the session attributes you need in @Async and pass them directly. This, by the way, is a much better design - avoid skipping the HttpSession object because it makes testing more difficult and your code is much less likely to be reused in the future.

+3
source

Source: https://habr.com/ru/post/1411001/


All Articles