To support the scoping of beans at the request
, session
, globalSession
, application
, and websocket
levels (web-scoped beans), some minor initial configuration is required before you define your beans. (This initial setup is not required for the standard scopes, singleton
and prototype
.)
为了支持beans的作用域界定在request
,session
,globalSession
, application
,和websocket
(即具有web作用域bean),定义你的beans之前,需要做少量的初始配置。(这是初始步骤对于标准作用域是不必要的,singleton
和prototype
)。
How you accomplish this initial setup depends on your particular Servlet environment.
如何完成此初始设置取决于您的特定Servlet环境。
If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the Spring DispatcherServlet
or DispatcherPortlet
, then no special setup is necessary: DispatcherServlet
and DispatcherPortlet
already expose all relevant state.
如果您访问Spring Web MVC框架内作用域的beans,实际上, 即由Spring处理的请求中DispatcherServlet
或DispatcherPortlet
,则不需要特殊的设置:DispatcherServlet
与DispatcherPortlet
已公开所有相关的状态。
If you use a Servlet 2.5 web container, with requests processed outside of Spring’s DispatcherServlet
(for example, when using JSF or Struts), you need to register the org.springframework.web.context.request.RequestContextListener
ServletRequestListener
. For Servlet 3.0+, this can be done programmatically via the WebApplicationInitializer
interface. Alternatively, or for older containers, add the following declaration to your web application’s web.xml
file:
如果您使用Servlet 2.5 Web容器,并且在Spring之外处理请求 DispatcherServlet
(例如,使用JSF或Struts时),则需要注册org.springframework.web.context.request.RequestContextListener
ServletRequestListener
。对于Servlet 3.0+,可以通过WebApplicationInitializer
接口以编程方式完成。或者,或者对于旧容器,将以下声明添加到Web应用程序的web.xml
文件中:
<web-app> ... <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> ... </web-app>
Alternatively, if there are issues with your listener setup, consider using Spring’s RequestContextFilter
. The filter mapping depends on the surrounding web application configuration, so you have to change it as appropriate.
或者,如果您的侦听器设置存在问题,请考虑使用Spring RequestContextFilter
。过滤器映射取决于周围的Web应用程序配置,因此您必须根据需要进行更改。
<web-app> ... <filter> <filter-name>requestContextFilter</filter-name> <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class> </filter> <filter-mapping> <filter-name>requestContextFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ... </web-app>
DispatcherServlet
, RequestContextListener
, and RequestContextFilter
all do exactly the same thing, namely bind the HTTP request object to the Thread
that is servicing that request. This makes beans that are request- and session-scoped available further down the call chain.
DispatcherServlet
,RequestContextListener
和RequestContextFilter
都在做同样的事情,即将HTTP请求对象绑定到Thread这个
为该请求提供服务的对象。这使得请求和会话范围的bean可以在调用链的下面进一步使用。