Tomcat源码分析(过滤器)filterchain filter(2010-01-21 15:46:16)
Tomcat的过滤器主要由Filter、FilterChain组成,FilterChain包含一个Filter数组.当Wrapper执行FilterChain的doFilter(request,response)方法时,FilterChain首先调用{dy}个Filter的doFilter(request,response,filterchain)方法,当{dy}个filter做完过滤操作后,它又会调用filterchain的doFilter方法,此时filterchain的当前filter已变为第二个filter,第二个filter又执行dofilter方法,依此类推,直至所有过滤器都执行完毕
1.接口
2.实现例子
过滤器可以在web.xml中进行配置
1.接口
- public
interface Filter { -
..... -
-
void doFilter throws( ServletRequest request, ServletResponse response, FilterChain chain ) IOException, ServletException; -
- }
-
- public
interface FilterChain { -
void doFilter throws( ServletRequest request, ServletResponse response ) IOException, ServletException; - }
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 implementsFilterChain { -
-
-
(pos < n) { -
-
ApplicationFilterConfig filterConfig = filters[pos++]; -
Filter filter = -
{ -
filter = filterConfig.getFilter(); -
-
-
filter.doFilter(request, response, -
} -
... -
} - }
-
-
- class
SampleFilter implementsFilter { -
........ -
void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) -
IOException, ServletException { -
-
something -
..... -
response传递给下一个过滤器进行过滤 -
chain.doFilter(request, response); -
} -
- }
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中进行配置
已投稿到: |
|
---|