参考博文 https://blog.csdn.net/wwwdc1012/article/details/83592323
Tomcat 过滤器中的责任链模式
Servlet 过滤器是可用于 Servlet 编程的 Java 类,可以实现以下目的:
在客户端的请求访问后端资源之前,拦截这些请求;
在服务器的响应发送回客户端之前,处理这些响应。
Servlet 定义了过滤器接口 Filter 和过滤器链接口 FilterChain 的源码如下
public interface Filter {
public void init(FilterConfig filterConfig) throws ServletException;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException;
public void destroy();
}
public interface FilterChain {
void doFilter(ServletRequest var1, ServletResponse var2) throws IOException, ServletException;
}
我们自定义一个过滤器的步骤
1)写一个过滤器类,实现 javax.servlet.Filter
接口
public class MyFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// 做一些自定义处理....
System.out.println("执行doFilter()方法之前...");
chain.doFilter(request, response); // 传递请求给下一个过滤器
System.out.println("执行doFilter()方法之后...");
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
2)在 web.xml
文件中增加该过滤器的配置,譬如下面是拦截所有请求
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.whirly.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
当启动 Tomcat 是我们的过滤器就可以发挥作用了。那么过滤器是怎样运行的呢?
Tomcat 有 Pipeline Valve机制,也是使用了责任链模式,
一个请求会在 Pipeline 中流转,Pipeline 会调用相应的 Valve 完成具体的逻辑处理;
其中的一个基础Valve为 StandardWrapperValve,
其中的一个作用是调用 ApplicationFilterFactory 生成 Filter链,
具体代码在 invoke 方法中
在运行过滤器之前需要完成过滤器的加载和初始化,以及根据配置信息生成过滤器链:
过滤器的加载具体是在 ContextConfig 类的 configureContext 方法中,
分别加载 filter 和 filterMap 的相关信息,并保存在上下文环境中;
过滤器的初始化在 StandardContext 类的 startInternal 方法中完成,
保存在 filterConfigs 中并存到上下文环境中;
请求流转到 StandardWrapperValve 时,在 invoke 方法中,
会根据过滤器映射配置信息,为每个请求创建对应的 ApplicationFilterChain,
其中包含了目标 Servlet 以及对应的过滤器链,
并调用过滤器链的 doFilter 方法执行过滤器
StandardWrapperValve
调用 ApplicationFilterFactory
为请求创建过滤器链并调用过滤器链的关键代码如下:
final class StandardWrapperValve extends ValveBase {
public final void invoke(Request request, Response response) throws IOException, ServletException {
// 省略其他的逻辑处理...
// 调用 ApplicationFilterChain.createFilterChain() 创建过滤器链
ApplicationFilterChain filterChain = ApplicationFilterFactory.createFilterChain(request, wrapper, servlet);
if (servlet != null && filterChain != null) {
// 省略
} else if (request.isAsyncDispatching()) {
request.getAsyncContextInternal().doInternalDispatch();
} else if (comet) {
filterChain.doFilterEvent(request.getEvent());
} else {
// 调用过滤器链的 doFilter 方法开始过滤
filterChain.doFilter(request.getRequest(), response.getResponse());
}
}
过滤器链 ApplicationFilterChain
的关键代码如下,过滤器链实际是一个 ApplicationFilterConfig
数组:
final class ApplicationFilterChain implements FilterChain, CometFilterChain {
private ApplicationFilterConfig[] filters = new ApplicationFilterConfig[0]; // 过滤器链
private Servlet servlet = null; // 目标
// ...
@Override
public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
if( Globals.IS_SECURITY_ENABLED ) {
// ...
} else {
internalDoFilter(request,response); // 调用 internalDoFilter 方法
}
}
private void internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
// Call the next filter if there is one
if (pos < n) {
// 从过滤器数组中取出当前过滤器配置,然后下标自增1
ApplicationFilterConfig filterConfig = filters[pos++];
Filter filter = null;
try {
filter = filterConfig.getFilter(); // 从过滤器配置中取出该 过滤器对象
if( Globals.IS_SECURITY_ENABLED ) {
final ServletRequest req = request;
final ServletResponse res = response;
Principal principal = ((HttpServletRequest) req).getUserPrincipal();
Object[] args = new Object[]{req, res, this};
SecurityUtil.doAsPrivilege("doFilter", filter, classType, args, principal);
} else {
// 调用过滤器的 doFilter,完成一个过滤器的过滤功能
filter.doFilter(request, response, this);
}
return; // 这里很重要,不会重复执行后面的 servlet.service(request, response)
}
// 执行完过滤器链的所有过滤器之后,调用 Servlet 的 service 完成请求的处理
if ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse)) {
if( Globals.IS_SECURITY_ENABLED ) {
} else {
servlet.service(request, response);
}
} else {
servlet.service(request, response);
}
}
// 省略...
}
过滤器:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("执行doFilter()方法之前...");
chain.doFilter(request, response); // 传递请求给下一个过滤器
System.out.println("执行doFilter()方法之后...");
}
当下标小于过滤器数组长度 n 时,说明过滤器链未执行完,所以从数组中取出当前过滤器,调用过滤器的 doFilter 方法完成过滤处理,在过滤器的 doFilter 中又调用 FilterChain 的 doFilter,回到 ApplicationFilterChain,又继续根据下标是否小于数组长度来判断过滤器链是否已执行完,未完则继续从数组取出过滤器并调用 doFilter 方法,所以这里的过滤链是通过嵌套递归的方式来串成一条链。
当全部过滤器都执行完毕,最后一次进入 ApplicationFilterChain.doFilter 方法的时候 pos < n 为false,不进入 if (pos < n) 中,而是执行后面的代码,判断 (request instanceof HttpServletRequest) && (response instanceof HttpServletResponse),若为 http 请求则调用 servlet.service(request, response); 来处理该请求。
处理完毕之后沿着调用过滤器的顺序反向退栈,分别执行过滤器中 chain.doFilter() 之后的处理逻辑,需要注意的是在 if (pos < n) 方法体的最后有一个 return;,这样就保证了只有最后一次进入 ApplicationFilterChain.doFilter 方法的调用能够执行后面的 servlet.service(request, response) 方法;