在最初接收的线程之外访问HttpSession

时间:2012-05-06 18:53:13

标签: java spring asynchronous httpsession

我正在使用Spring 3.当控制器获取请求时,它将控制传递给在Service bean中用someMethod()注释的方法@Async,然后返回。当我访问someMethod() HttpSession对象时,我收到此异常

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.

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

HttpSession对象本身可用于多个线程(但线程安全,因此必须同步)。然而Spring正在做一些额外的魔术,例如当你有session - 范围豆。即它使用下面的ThreadLocal来绑定当前会话与线程。

我不知道你的具体情况是什么,但显然当你在另一个线程中时,Spring试图从这个HttpSession中检索ThreadLocal - 这显然是失败的。

解决方案很简单 - 在@Async方法中提取您需要的会话属性并直接传递它们。这是更好的设计方式 - 避免传递HttpSession对象,因为它会使测试变得更难,而且您的代码将来不太可能被重用。