Tomcat的filter调用主要实现类和方法是
ApplicationFilterChain.internalDoFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException
该类内部维护
-
一个filter数组
-
1个servlet(spring应用中该servlet类是org.springframework.web.servlet.DispatcherServlet)
-
1个int变量pos来记录下一个需要执行的filter在数组中的下标
若pos大于等于filter数组长度(包括filter数组为空的情况),则直接调用servlet.service方法,否则调用下一个filter。
filter内部的doFilter方法里,需要调用ApplicationFilterChain.doFilter来执行其后的的filter,若不调用,则后续filter及servlet均不执行。
伪代码及流程图如下。注意蓝色线条组成的循环,是filter通过调用 filterChain.doFilter循环进入了ApplicationFilterChain
![](https://i-blog.csdnimg.cn/blog_migrate/27b8f99dc157d92d22ab7bace3a5dd57.png)