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

我正在使用Spring 3.当控制器获得请求时,它将控制传递给在Service bean中使用@Async注释的方法someMethod() ,然后返回。 当我访问someMethod() HttpSession对象时,我收到此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将当前会话与线程绑定。

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

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