Tomcat源码分析(过滤器)

Tomcat的过滤器主要由Filter、FilterChain组成,FilterChain包含一个Filter数组.当Wrapper执行FilterChain的doFilter(request,response)方法时,FilterChain首先调用第一个Filter的doFilter(request,response,filterchain)方法,当第一个filter做完过滤操作后,它又会调用filterchain的doFilter方法,此时filterchain的当前filter已变为第二个filter,第二个filter又执行dofilter方法,依此类推,直至所有过滤器都执行完毕

1.接口
public interface Filter {
        .....       
        //执行过滤
        public void doFilter ( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException;

}

public interface FilterChain {
    public void doFilter ( ServletRequest request, ServletResponse response ) throws IOException, ServletException;
}


2.实现例子
class ApplicationFilterChain implements FilterChain {
   
   //pos为当前filter的所在位置,n为filters数组的长度
   if (pos < n) {
            //pos++执行后,把filterchain的当前filter指向下一个
            ApplicationFilterConfig filterConfig = filters[pos++];
            Filter filter = null;
            try {
                filter = filterConfig.getFilter();

                //filter执行过滤操作
                filter.doFilter(request, response, this);
            }
            ...
   }
}


class SampleFilter implements Filter {
      ........
      public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)
        throws IOException, ServletException {
         
         //do something 
         .....
         //request, response传递给下一个过滤器进行过滤
         chain.doFilter(request, response);
    }
      
}


过滤器可以在web.xml中进行配置

你可能感兴趣的:(tomcat,Web,xml)