对Filter执行顺序的测试

Filter执行顺序

本文主要对 Filter 在前端提交后过滤器的顺序进行测试

涉及的主要测试为 xml 配置测试及 注解 配置测试

注解 及 xml配置共存情况

  • xml文件配置
<filter>
    <filter-name>filter4</filter-name>
    <filter-class>filtertest.Demo4</filter-class>
</filter>
<filter-mapping>
    <filter-name>filter4</filter-name>
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>
<filter>
    <filter-name>filter3</filter-name>
    <filter-class>filtertest.Demo3</filter-class>
</filter>
<filter-mapping>
    <filter-name>filter3</filter-name>
    <url-pattern>/servlet/*</url-pattern>
</filter-mapping>
  • 各个过滤器配置
@WebFilter("/servlet/*")
public class Demo1 implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("fliter1");
        chain.doFilter(request, response);
        System.out.println("fliter1back");
    }
}
@WebFilter("/servlet/*")
public class Demo2 implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("fliter2");
        chain.doFilter(request, response);
        System.out.println("fliter2back");
    }
}
public class Demo3 implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("fliter3");
        chain.doFilter(request, response);
    }
}
public class Demo4 implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("fliter4");
        chain.doFilter(request, response);
    }
}
  • 测试结果稳定

    fliter4
    fliter3
    fliter1
    fliter2
    fliter2back
    fliter1back

  • 猜测结论

    • xml一定优先注解

    • back方法执行顺序和触发顺序正好相反

    • xml越上面配置越早触发

    • 注解可能是因为名字字母的原因

      • 测试将 Demo2 类前面加一个 a 这样就是 ADemo2

      • xml配置更换 Demo3 和 Demo4 的位置

        • 猜测结果

          fliter3
          fliter4
          fliter2
          fliter1
          fliter1back
          fliter2back

  • 经测试结论正确

    • 结论
      • xml一定优先注解
      • back方法执行顺序和触发顺序正好相反
      • xml越上面配置越早触发
      • 注解根据字母顺序触发
posted @ 2021-07-30 17:11  Rainful  阅读(55)  评论(0编辑  收藏  举报