Filter

Filter,过滤器,可以在servlet之前拦截request

注册Filter:context.xml

<filter>
    <filter-name>urlFilter</filter-name>
    <filter-class>com.stt.common.filter.UrlFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>urlFilter</filter-name>
    <url-pattern>/user/testFilter.do</url-pattern>
</filter-mapping>

定义Filter:
实现Filter接口,Filter接口有三个方法
void init(javax.servlet.FilterConfig arg0);
void destroy();
void doFilter(ServletRequest request, ServletResponse response, FilterChain chain);
核心方法doFilter:
在该方法中可以对request,response进行具体的处理。之后可以调用chain.doFilter(request, response)将请求递交给下一个Filer对象。

Filter数据流(举例说明):
注册两个Filter,监听同一个url

FilterA implements Filter
{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException 
    {
        System.out.println("------------");
        filterChain.doFilter(request, response);
        System.out.println("------------");

    }
    ...
}
FilterB implements Filter
{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException 
    {
        System.out.println("+++++++++++");
        filterChain.doFilter(request, response);
        System.out.println("+++++++++++");

    }
    ...
}

并且在servlet中打印“哈哈baizq”

输出:

------------ +++++++++++
哈哈baizq +++++++++++
------------

所以在调用filterChain.doFilter(request, response);时,程序控制权已经递交给下一个Filter,如果已经没有Filter,则交给Servlet处理
Servlet处理完之后返回给最近的Filter,执行filterChain.doFilter(request, response);下面的代码直至doFilter执行结束,再返回上一个Filter做同样的事情

你可能感兴趣的:(filter)