转载

Springboot拦截器的使用

Springboot拦截器的使用

  1. 引入springboot-starter-web
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
     <exclusions>
         <exclusion>
             <artifactId>org.springframework.boot</artifactId>
             <groupId>spring-boot-start-tomcat</groupId>
         </exclusion>
     </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
  1. 创建拦截器

    @Component
      
    public class LogInterceptor implements HandlerInterceptor { 
      static Logger logger = LoggerFactory.getLogger(LoggerFactory.class);
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            logger.info("请求的路径为: "+ request.getRequestURI() + ", 请求的参数为:" + JSON.toJSONString(request.getParameterMap()));
            return true;
        }
    }
  2. 创建WebMvcConfigurer。

    WebMvcConfigurer配置类其实是 Spring 内部的一种配置方式,采用 JavaBean 的形式来代替传统的 xml 配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个 配置 类并实现 WebMvcConfigurer 接口;

    @Configuration
    public class RequestLogConfiguration {
      
        @Autowired
        private LogInterceptor logInterceptor;
    
        @Bean
        public WebMvcConfigurer webMvcConfigurer(){
            return new WebMvcConfigurer() {
                @Override
                public void addInterceptors(InterceptorRegistry registry) {
                    registry.addInterceptor(logInterceptor).addPathPatterns("/**");
                }
            };
        }
    
    }

    还有第二种方式实现,直接用WebConfiguration implements WebMvcConfigurer 重写addInterceptors方法

原文  https://segmentfault.com/a/1190000022164918
正文到此结束
Loading...