java - 在原始接收线程之外访问 HttpSession

标签 java spring asynchronous httpsession

我正在使用 Spring 3。当 Controller 收到请求时,它将控制传递给方法 someMethod() 在服务 bean 中用 @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.

我该如何解决?

最佳答案

HttpSession 对象本身可以在多线程中使用(但不是线程安全的,因此必须同步)。然而 Spring 正在做一些额外的魔法,例如当你有 session 作用域的 bean 时。即它使用下面的ThreadLocal将当前 session 与线程绑定(bind)。

我不知道你的确切场景是什么,但显然当你在另一个线程中时,Spring 试图从这个 ThreadLocal 中检索 HttpSession - 这显然失败了。

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

关于java - 在原始接收线程之外访问 HttpSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10473254/

相关文章:

java - JPA Criteria query eager fetch associated entities using a SINGLE query with join 而不是多个查询

spring - 将 @Component 添加到自定义 Spring Security 过滤器的含义是什么

java - 如何获取 Autowiring 的bean的范围

python - 在 asyncio 事件循环中运行协程和线程 : Errors while exiting

iphone - 弹出 UIViewController 时处理打开的异步 Web 请求 (AFNetworking)

java - 从另一个类调用变量时是否可以避免使用 "static"?

基于代理的模型中的 Java NullPointerException

javascript - Spring Boot GetMapping 404

swift - 使用或不使用 DispatchQueue 不加载 TableView 图像

java - 在静态方法中定义内部类的目的是什么?