zoukankan      html  css  js  c++  java
  • 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方法

  • 相关阅读:
    readonly
    cut
    finger
    ping fping
    chmod/chown/chgrp/chattr
    synchronized 和 volatile 比较
    volatile的适用场合
    volatile的适用场合
    细说Java多线程之内存可见性
    SDUT2139图结构练习——BFS——从起始点到目标点的最短步数
  • 原文地址:https://www.cnblogs.com/undefined22/p/12579197.html
Copyright © 2011-2022 走看看