测试源码如下:
1 package com.FilterTest.Filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 12 public class TestFilter implements Filter { 13 14 @Override 15 public void init(FilterConfig filterConfig) throws ServletException { 16 print("init"); 17 } 18 19 @Override 20 public void doFilter(ServletRequest request, ServletResponse response, 21 FilterChain chain) throws IOException, ServletException { 22 print("do filter"); 23 chain.doFilter(request, response); 24 print("do filter End!"); 25 } 26 27 @Override 28 public void destroy() { 29 print("destory!"); 30 } 31 32 void print(String info){ 33 System.out.println(info+" Thread Name:"+Thread.currentThread().getName()); 34 } 35 }
访问首页后调试控制台输出:
init 和destroy在服务重启的时候执行,且只有一次:
访问主页后:
do filter Thread Name:http-nio-8081-exec-11
Second Filter----do Filter http-nio-8081-exec-11
Second Filter----do Filter End! http-nio-8081-exec-11
do filter End! Thread Name:http-nio-8081-exec-11
do filter Thread Name:http-nio-8081-exec-12
Second Filter----do Filter http-nio-8081-exec-12
Pages Filter----do Filter http-nio-8081-exec-12
Pages Filter----do Filter End! http-nio-8081-exec-12
Second Filter----do Filter End! http-nio-8081-exec-12
do filter End! Thread Name:http-nio-8081-exec-12
Filter是根据配置前后然后根据Servlet域大小来先后执行!