Filter执行过程是什么

Filter执行的顺序
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
马克-to-win:根据上面的说明“Filter的拦截的工作过程”的图,我们对Filter的Helloworld例子做一个小小的扩展(增加了一个 MarkToWinFilter2,代码和MarkToWinFilter几乎一样),来说明Filter的顺序,结论:filter-mapping在Web.xml中的顺序决定了Filter执行的顺序。



例 1.2.3

Web.xml中增加下一段:

     <filter>
        <filter-name>MarkToWinFilter2</filter-name>
        <filter-class>com.MarkToWinFilter2</filter-class>
    </filter>
    <filter>
        <filter-name>MarkToWinFilter</filter-name>
        <filter-class>com.MarkToWinFilter</filter-class>
    </filter>
  <filter-mapping>
      <filter-name>MarkToWinFilter</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
    <filter-mapping>
      <filter-name>MarkToWinFilter2</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>



package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MarkToWinFilter2 implements Filter {
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        out.println("之前 filterChain.doFilter2");
        System.out.println("之前 filterChain.doFilter2");
        chain.doFilter(request, response);
        System.out.println("之后 filterChain.doFilter2");
        out.println("之后 filterChain.doFilter2");
    }
    public void init(FilterConfig fConfig) throws ServletException {
    }
}







在浏览器中,当运行home.jsp时,浏览器中输出的结果是:

之前 filterChain.doFilter 之前 filterChain.doFilter2
这是在home.jsp
之后 filterChain.doFilter2 之后 filterChain.doFilter



同时Console中输出的结果是:

之前 filterChain.doFilter
之前 filterChain.doFilter2
inside jsp
之后 filterChain.doFilter2
之后 filterChain.doFilter