什么是 DelegatingFilterProxy
?
DelegatingFilterProxy
是 Spring 提供的一个特殊的过滤器,它起到了桥梁的作用,可以让你在 Spring 容器中管理 Servlet 容器中的过滤器。
为什么需要 DelegatingFilterProxy
?
通常情况下,Servlet 容器中的过滤器是由 Servlet 容器直接管理的,但这样有一些局限性,比如你不能方便地使用 Spring 的依赖注入来管理过滤器的依赖。通过使用 DelegatingFilterProxy
,你可以把过滤器放到 Spring 容器中管理,享受 Spring 提供的各种功能。
怎么理解 DelegatingFilterProxy
的工作流程?
- 配置过滤器:你在
web.xml
文件中配置了一个过滤器,但这个过滤器实际上是DelegatingFilterProxy
。 - 委托处理:
DelegatingFilterProxy
会将请求委托给 Spring 容器中定义的某个具体的过滤器(这个过滤器是一个 Spring Bean)。 - Spring 管理:这个具体的过滤器可以使用 Spring 的各种功能,比如依赖注入、事务管理等等。
示例:使用 DelegatingFilterProxy
配置 Spring Security
假设我们需要在一个 Spring 项目中使用 Spring Security 来管理权限验证。我们将通过 DelegatingFilterProxy
将 Spring Security 的过滤器配置到 Spring 容器中。
1. 配置 web.xml
在 web.xml
文件中,我们配置一个 DelegatingFilterProxy
,并指定 Spring Security 的过滤器 Bean 名称。
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 配置 DelegatingFilterProxy -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 其他配置 -->
</web-app>
2. 配置 Spring Bean
在 Spring 的配置文件中,我们定义 UserService
和 CustomSecurityFilter
Bean,并使用依赖注入。
applicationContext.xml
示例:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
xmlns:sec="http://www.springframework.org/schema/s