在原始接收线程之外访问HttpSession [英] Accessing HttpSession outside of the originally receiving thread
问题描述
我正在使用Spring3.当控制器获取请求时,它将控制权传递给Service Bean中以@Async
注释的方法someMethod()
,然后返回.当我在someMethod()
HttpSession对象中访问时,收到此异常
I'm using Spring 3. When controller gets requests it passes control to method someMethod()
annotated with @Async
in Service bean and then returns. When I access in someMethod()
HttpSession object I receive 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.
我该如何解决?
推荐答案
HttpSession
对象本身可以在多个线程中使用(但不是线程安全的,因此必须同步).但是Spring正在做一些额外的魔术,例如当您具有session
范围的bean时.即,它使用下面的ThreadLocal
来将当前会话与线程绑定.
The HttpSession
object itself can be used in multiple threads (but is not thread-safe and therefore must be synchronized). However Spring is doing some extra magic e.g. when you have session
-scoped beans. Namely it uses ThreadLocal
underneath to bind current session with thread.
我不知道您的确切情况是什么,但是显然,当您在另一个线程中时,Spring会尝试从此ThreadLocal
中检索HttpSession
-显然会失败.
I don't know what is your exact scenario, but apparently Spring tries to retrieve HttpSession
from this ThreadLocal
while you are in another thread - which obviously fails.
解决方案很简单-在@Async
方法中提取所需的会话属性,然后直接传递它们.顺便说一下,这是更好的设计-避免传递HttpSession
对象,因为这会使测试变得更加困难,并且将来代码的重用性也将大大降低.
The solution is simple - extract session attributes you need in @Async
method and pass them directly. This is by the way much better design - avoid passing HttpSession
object around because it makes testing harder and your code is much less likely to be reused in the future.
这篇关于在原始接收线程之外访问HttpSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!