class DelegatingFilterProxy

时间:2023-03-09 17:01:06
class DelegatingFilterProxy
/**
* Proxy for a standard Servlet Filter, delegating to a Spring-managed bean that
* implements the Filter interface. Supports a "targetBeanName" filter init-param
* in {@code web.xml}, specifying the name of the target bean in the Spring
* application context.
*
* <p>{@code web.xml} will usually contain a {@code DelegatingFilterProxy} definition,
* with the specified {@code filter-name} corresponding to a bean name in
* Spring's root application context. All calls to the filter proxy will then
* be delegated to that bean in the Spring context, which is required to implement
* the standard Servlet Filter interface.
*
* <p>This approach is particularly useful for Filter implementation with complex
* setup needs, allowing to apply the full Spring bean definition machinery to
* Filter instances. Alternatively, consider standard Filter setup in combination
* with looking up service beans from the Spring root application context.
*
* <p><b>NOTE:</b> The lifecycle methods defined by the Servlet Filter interface
* will by default <i>not</i> be delegated to the target bean, relying on the
* Spring application context to manage the lifecycle of that bean. Specifying
* the "targetFilterLifecycle" filter init-param as "true" will enforce invocation
* of the {@code Filter.init} and {@code Filter.destroy} lifecycle methods
* on the target bean, letting the servlet container manage the filter lifecycle.
*
*/

1. 这是一个过滤器代理 <filter-name>shiroFilter</filter-name> 的值会传递给 targetBeanName ,

targetBeanName = "shiroFilter";

shiroFilter 是由Spring管理的bean,并实现了Filter 接口。

2. 所有的请求会被转发给shiroFilter

3. 当过滤器配置复杂的时候,这个代理非常有用

4. 通过指定 targetFilterLifecycle = "true"; 来强制调用过滤器的初始化方法和销毁方法,从而被servlet 纳入管理

实例:

web.xml 部分代码

    <filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>

applicationContext-Shiro.xml  代码片段

    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="webSecurityManager" />
</bean>