SpringBoot添加拦截器

拦截器不是一个普通的属性,而是一个类,因此需要用到java的配置方式。根据SpringBoot官方文档的说明,我们需要实现WebMvcConfigurer并添加@Configuration注解来添加SpringMvc配置。

SpringBoot添加拦截器的步骤

1、创建Maven工程,添加父工程和依赖(此处为JDK1.8的环境)

2、创建启动类

3、定义拦截器(添加日志,设置日志级别),实现WebMvcConfigurer接口

4、运行查看


一、pom.xml配置



    4.0.0

    springBoot_Interceptor
    DemoInterceptor
    1.0-SNAPSHOT

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.0.RELEASE
    

    
    
    
        org.springframework.boot
        spring-boot-starter-web
    

    

二、启动类

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}


三、定义拦截器

package com.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Configuration
public class MvcConfig implements WebMvcConfigurer {
   //配置日志
    private static final Logger logger= LoggerFactory.getLogger(MvcConfig.class);
   
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                //设置日志级别
                logger.debug("前置方法被执行");
                return true;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                logger.debug("后置方法被执行");
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                logger.debug("最终方法被执行");
            }
        });
    }
}

此处配置了日志,并设置日志级别为debug。并采用匿名内部类的方法。

此时日志并不能被读取,原因在于日志的默认级别为info,此处的是debug,而debug级别比info低。因此需要在application.yml中配置日志级别。注意控制日志级别在哪个包下。

SpringBoot添加拦截器_第1张图片


四、测试查看

package com.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("hello")
    public String HelloController(){
        System.out.println("handler执行了");
        return "Hello,springBoot!";
    }
}

运行结果


你可能感兴趣的:(SpringBoot添加拦截器)