【问题标题】:Accessing HttpServletRequest request in child thread在子线程中访问 HttpServletRequest 请求
【发布时间】:2014-09-26 06:29:59
【问题描述】:

我有一个 Web 应用程序,我在其中使用 ScheduledThreadPoolExecutor 来安排稍后执行的一些逻辑(可能在原始 Web 请求结束之后)。是否可以在子线程中访问/使用原始请求的 HttpServletRequest(通过 ScheduledThreadPoolExecutor 上的“schedule”调用创建)?

我尝试在函数在子线程中运行的类中自动装配 HttpServletRequest,但出现以下错误(我理解原因)

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.

有什么办法吗? RequestContextFilter可以用吗?

【问题讨论】:

  • 没有。请求对象和请求范围的 spring bean 不应该在请求处理后使用,甚至在单独的线程中也不应该使用。提取计划作业所需的数据,然后使用此数据将任务提交给执行程序。
  • 可以使用[BeanUtils] (grepcode.com/file/repo1.maven.org/maven2/commons-beanutils/…) 复制HttpServletRequest 对象吗?
  • 为什么在计划作业中需要一个 HttpServletRequest 对象?将计划作业所需的数据提取到一个对象,然后将该对象传递给该作业。

标签: java multithreading spring servlets requestcontext


【解决方案1】:

似乎您想要完成的是让 HTTP 连接保持打开状态,同时在单独的线程中异步处理请求的处理?

在这种情况下,您可能想看看 Spring MVC 中的 DeferedResult 支持 - http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/context/request/async/DeferredResult.html - 也在这里解释 - http://java.dzone.com/articles/long-polling-spring-32s

【讨论】:

    猜你喜欢
    • 2016-09-29
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2016-09-13
    • 2018-09-07
    • 2012-07-25
    • 2019-11-08
    • 1970-01-01
    相关资源
    最近更新 更多