美文网首页
SpringBoot 自定义拦截器 Interceptor

SpringBoot 自定义拦截器 Interceptor

作者: lconcise | 来源:发表于2019-06-29 14:41 被阅读0次

    简介

    拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作。在SpringMVC中就是依赖于SpringMVC框架。在实现上基于Java的反射机制,属于面向切面编程(AOP)的一种运用。

    主要工作场景

    拦截器可以获取IOC容器中的各个bean,而过滤器就不行,所以在拦截器里注入一个service,可以调用业务逻辑。
    拦截器只能对controller请求进行拦截,对其他的一些比如直接访问静态资源的请求则没办法进行拦截处理。

    实现

    1. 定义自己拦截器

    /**
     * Created by liusj 2019/6/29
     */
    @Log
    public class MyInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.info("MyInterceptor == preHandler ");
            long startTime = System.nanoTime();
            request.setAttribute("startTime", startTime);
            return super.preHandle(request, response, handler);
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.info("MyInterceptor == postHandle ");
            super.postHandle(request, response, handler, modelAndView);
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            log.info("MyInterceptor == afterCompletion ");
    
            Long startTime = (Long) request.getAttribute("startTime");
            long endTime = System.nanoTime();
            // 打印出接口请求时间
            log.info("This method expired :" + (endTime - startTime) / 1000000 + " 毫秒");
    
            super.afterCompletion(request, response, handler, ex);
        }
    }
    

    2. 配置(添加到Spring中)

    @Configuration
    public class MyMvcConfigure extends WebMvcConfigurerAdapter {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInterceptor()).addPathPatterns("/");// 添加拦截路径
            super.addInterceptors(registry);
        }
    }
    

    由于SpringBoot2中WebMvcConfigurerAdapter过时@Deprecated,这里通过实现WebMvcConfigurer来实现拦截器的配置。

    /**
     * Created by liusj 2019/6/29
     */
    @Configuration
    public class MyMvcConfigure2 implements WebMvcConfigurer {
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new MyInterceptor()).addPathPatterns("/");// 添加拦截路径
        }
    }
    

    测试

    @SpringBootApplication
    @RestController
    @Log
    public class Application {
    
        @RequestMapping(value = "/")
        public String home() {
            log.info("接口请求");
            return "Hello Interceptor World";
        }
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
    }
    

    测试结果

    image.png

    代码地址:https://github.com/lbshold/springboot/blob/master/Spring-Boot-Interceptor.zip

    参考文献:
    https://www.cnblogs.com/junzi2099/p/8022058.html

    https://yq.aliyun.com/articles/688309?spm=a2c4e.11155435.0.0.78a13da0ZMVALr

    相关文章

      网友评论

          本文标题:SpringBoot 自定义拦截器 Interceptor

          本文链接:https://www.haomeiwen.com/subject/czpscctx.html