servlet的過濾器filter類

H小瑞發表於2017-07-22
  • 先上程式碼
public class FilterA implements Filter {
    public FilterA() {
        System.out.println("例項化filterA");
    }

    public void destroy() {
        System.out.println("銷燬filterA");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("經過FilterA的前處理");
        chain.doFilter(request, response);
        System.out.println("到達filterA的後處理");
    }

    public void init(FilterConfig fConfig) throws ServletException {
        System.out.println("初始化FilterA");
    }

}



public class FilterB implements Filter {
    public FilterB() {
        System.out.println("例項化filterB");
    }

    public void destroy() {
        System.out.println("銷燬filterB");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("經過FilterB的前處理");
        chain.doFilter(request, response);
        System.out.println("到達filterB的後處理");
    }

    public void init(FilterConfig fConfig) throws ServletException {
        System.out.println("初始化FilterB");
    }

}


public class FilterC implements Filter {
    public FilterC() {
        System.out.println("例項化filterC");
    }

    public void destroy() {
        System.out.println("銷燬filterC");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println("經過FilterC的前處理");
        chain.doFilter(request, response);
        System.out.println("到達filterC的後處理");
    }

    public void init(FilterConfig fConfig) throws ServletException {
        System.out.println("初始化FilterC");
    }

}


  • web.xml的配置順序(注意順序):有先後順序,而且如果同一個攔截器同時使用註解和web.xml配置會在啟動專案時例項化兩次
  <!--配置過濾器A  -->
  <filter>
    <filter-name>FilterA</filter-name>
    <filter-class>com.zhiyou100.crm.filter.FilterA</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>FilterA</filter-name>
    <url-pattern>/test.jsp</url-pattern>
  </filter-mapping>

   <!--配置過濾器B -->
  <filter>
    <filter-name>FilterB</filter-name>
    <filter-class>com.zhiyou100.crm.filter.FilterB</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>FilterB</filter-name>
    <url-pattern>/test.jsp</url-pattern>
  </filter-mapping>

   <!--配置過濾器c  -->
  <filter>
    <filter-name>FilterC</filter-name>
    <filter-class>com.zhiyou100.crm.filter.FilterC</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>FilterC</filter-name>
    <url-pattern>/test.jsp</url-pattern>
  </filter-mapping>

啟動伺服器:
例項化FilterA
初始化FilterA
例項化FilterB
初始化FilterB
例項化FilterC
初始化FilterC


瀏覽器訪問web應用的test.jsp
經過FilterA的前處理
經過FilterB的前處理
經過FilterC的前處理
到達filterC的後處理
到達filterB的後處理
到達filterA的後處理

























相關文章