最近在学习shiro的时候看到了一个比较有用的filter-------------org.springframework.web.filter.DelegatingFilterProxy
他能将filter的部分配置放到applicationContext.xml中去,当然如果filter的配置项比较简单(key-value),可以直接在web.xml中配置
在<filter>中加入一下配置即可
<span style="font-size:18px;"> <init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param></span>
如果考虑比如说ilter的配置比较复杂或者filter的配置存在依赖项,则前面这种方式完全不足以应付这种场景。DelegatingFilterProxy则解决了这样的问题,
配置的应用如下:
web.xml中:
<span style="font-size:18px;"> <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></span>
applicationContext中:
<span style="font-size:18px;"> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/" />
<property name="filterChainDefinitions">
<value>
/login = authc
/logout = logout
/static/** = anon
/api/** = anon
/register/** = anon
/admin/** = roles[admin]
/** = user
</value>
</property>
</bean></span>
其中web.xml中<filter-name>的值必须和applicationContext.xml中bean id的值相同即可。
读者也可以猜测到spring内部是怎么干的,简单的说就是在filter初始化的时候,拿到上下文applicationContext,然后获取web.xml中的<filter-name>配置项,通过getBean方法就获取到了applicationContext.xml中对应的filter.