gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:10:55 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com