SpringBoot 拦截器Interceptor实战

SpringBoot2.0后拦截器实现方式

第一步:创建一个类MyInterceptor实现HandlerInterceptor接口,并重写方法

public class MyInterceptor implements HandlerInterceptor {

    /**
     * 调用Controller某个方法之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor ---------> 请求之前拦截");
        return true;
    }

    /**
     * Controller之后调用,视图渲染之前,如果控制器Controller出现了异常,则不会执行此方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyInterceptor ---------> 请求之后,视图渲染之前拦截");
    }

    /**
     * 不管有没有异常,这个afterCompletion都会被调用,用于资源清理
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyInterceptor ---------> 请求之后拦截,而且一定执行");
    }
}

第二步:创建一个配置类InterceptorConfig实现WebMvcConfigurer接口,重写addInterceptors方法

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/api/*/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/api/*/**");
    }
}

注意:SpringBoot2.0版本之前是 实现 WebMvcConfigurerAdapter 类的方式,2.0版本后这种方式被废弃了

测试:启动项目,访问 http://localhost:8080/api/v1/test

@RestController
public class TestController {

    @RequestMapping("/api/v1/test")
    public Object test(){
        System.out.println("controller ----------> 正在执行");
        return "访问成功!";
    }
}

结果:
SpringBoot 拦截器Interceptor实战_第1张图片

过滤器和拦截器区别与执行顺序

  • Filter是基于函数回调 doFilter(),而Interceptor则是基于AOP思想。
  • Filter在只在Servlet前后起作用,而Interceptor够深入到方法前后、异常抛出前后等。
  • Filter依赖于Servlet容器即web应用中,而Interceptor不依赖于Servlet容器所以可以运行在多种环境。
  • 在接口调用的生命周期里,Interceptor可以被多次调用,而Filter只能在容器初始化时调用一次。

Filter和Interceptor的执行顺序
SpringBoot 拦截器Interceptor实战_第2张图片

你可能感兴趣的:(SpringBoot)