欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Filter,Interceptor,AOP 区别与实例

程序员文章站 2022-07-15 15:39:31
...
filter interceptor aspect
入参 ServletRequest, ServletResponse HttpServletRequest , HttpServletResponse , Object handler ProceedingJoinPoint
原理 依赖于servlet容器,与框架无关 Spring框架拦截器,基于Java反射机制 动态代理(jdk动态代理/cglib)
范围 RESTful api RESTful api Spring Bean
  • 顺序:Filter -> Interceptor -> ControllerAdvie -> Aspect -> Controller -> Aspect -> ControllerAdvie -> Interceptor -> Filter
    *ps: ControllerAdvie 是controller的增强,和ExceptionHandler一起用来做全局异常。

Interceptor

  • 用法
  1. 继承HandlerInterceptorAdapter(是HandlerInterceptor接口的实现类,有默认的空实现,可以*选择自己需要的method去实现)
public class MyInterceptor extends HandlerInterceptorAdapter{
    @Override
    //如果preHandle返回false,这个url请求的controller方法不会进去(被拦截)
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
    • SpringBoot 项目:
      继承WebMvcConfigurerAdapter(是WebMvcConfigurer接口的实现类),加@Configuration注解,引入写好的Interceptor,调用addInterceptors方法。
@Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
    @Autowired
    private MyInterceptor myInterceptor;
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor)
                .addPathPatterns("/url1/**", "/url2/**")
                .excludePathPatterns("/url1/exclude");
    }
    super.addInterceptors(registry);
}
  • 非SpringBoot:
<mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/url/**" />
            <bean class="path.MyInterceptor" />
        </mvc:interceptor>
</mvc:interceptors>

AOP

  • 用法
    @Aspect @Component @Pointcut @Around @Before...
@Component
@Aspect
public class MyAspect {
    @Pointcut("execution(public * com.citi..controller..*Controller.*(..) ) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointcut() {
    }
    @Around("pointcut()")
    public Object function(ProceedingJoinPoint joinPoint) throws Throwable {
        // do something
        // 获取增强的类
        // 获取增强的方法名
        // 获取增强方法的参数
        return joinPoint.proceed();  //继续执行被拦截方法
    }
}

Filter

  • 用法
    实现Filter接口,或继承其实现类
    (eg: GenericFilterBean -> OncePerRequestFilter -> AbstractRequestLoggingFilter)
    @Component
    public class MyFilter implements Filter {
        private Logger logger = LoggerFactory.getLogger(getClass());
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            // do something
            chain.doFilter(request, response); //继续执行 
        }     
        @Override    
        public void destroy() {        
        }

转载于:https://www.jianshu.com/p/fbde79d76709