问题:
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.
查询:
public class RequestContextListener extends Object implements ServletRequestListener
Servlet listener that exposes the request to the current thread, through both LocaleContextHolder
and
RequestContextHolder
. To be registered as listener in web.xml
.
Alternatively, Spring‘s RequestContextFilter
and Spring‘s DispatcherServlet
also expose the same request
context to the current thread. In contrast to this listener, advanced options are available there (e.g.
"threadContextInheritable"). This listener is mainly for use with third-party servlets, e.g. the JSF FacesServlet.
Within Spring‘s own web support, DispatcherServlet‘s processing is perfectly sufficient.
解释
疑问:在介绍webApplicationContext初始化时,我们已经通过ContextLoaderListener将web容器与
spring容器整合,为什么这里又要引入一个额外的RequestContextListener以支持Bean的另外3个作用域呢?
在整合spring容器时使用ContextLoaderListener,它实现了ServletContextListener监听器接口,
ServletContextListener只负责监听web容器启动和关闭的事件。
而RequestContextListener实现ServletRequestListener监听器接口,该监听器监听HTTP请求事件,web服务器
接收的每一次请求都会通知该监听器。
spring容器启动和关闭操作由web容器的启动和关闭事件触发,但如果spring容器中的Bean需要request,session,globalsession
作用域的支持,spring容器本身就必须获得web容器的HTTP请求事件,以HTTP请求的事件驱动Bean作用域的控制逻辑。