过滤器和拦截器的区别

2018-03-25  本文已影响37人  隔壁老王的隔壁啊

摘自知乎

过滤器(Filter):当你有一堆东西的时候,你只希望选择符合你要求的某一些东西。定义这些要求的工具,就是过滤器。
拦截器(Interceptor):在一个流程正在进行的时候,你希望干预它的进展,甚至终止它进行,这是拦截器做的事情。
监听器(Listener):当一个事件发生的时候,你希望获得这个事件发生的详细信息,而并不想干预这个事件本身的进程,这就要用到监听器。

区别:
①过滤器是javaweb中的概念,拦截器是spring中的概念。
②过滤器是基于回调实现的,拦截器是基于反射实现。
③过滤器的核心是doFilter()方法,拦截器的核心是有三个方法:preHandle(),postHandle(),afterCompletion()更加细化。

过滤器可以将其理解成一个chain,当添加多个过滤器时,只有调用了FilterChain类的 doFilter()方法才进行下去。
拦截器有三个方法,我们假设添加两个拦截器如下:

public class MyInterceptor1 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("MyInterceptor1 preHandle method execute");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("MyInterceptor1 postHandle method execute");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("MyInterceptor1 afterCompletion method execute");
    }
}


public class MyInterceptor2 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        System.out.println("MyInterceptor2 preHandle method execute");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        System.out.println("MyInterceptor2 postHandle method execute");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        System.out.println("MyInterceptor2 afterCompletion method execute");
    }
}

运行结果:

MyInterceptor1 preHandle method execute
MyInterceptor2 preHandle method execute
MyInterceptor2 postHandle method execute
MyInterceptor1 postHandle method execute
MyInterceptor2 afterCompletion method execute
MyInterceptor1 afterCompletion method execute

上一篇下一篇

猜你喜欢

热点阅读