SpringBoot配置拦截器

时间:2022-04-02 06:48:40

【配置步骤】

1.为类添加注解@Configuration,配置拦截器

2.继承WebMvcConfigurerAdapter类

3.重写addInterceptors方法,添加需要拦截的请求

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //表示拦截所有的请求
        registry.addInterceptor(new InterceptorTest()).addPathPatterns("/*/**");
        super.addInterceptors(registry);
    }
}
public class InterceptorTest implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
            Object arg2) throws Exception {
        System.out.println("拦截成功");
        return false;
    }
        //HandlerInterceptor仍有其它方法,已省略
}

【测试拦截器】

1.配置mapping方法

    @RequestMapping("/interceptor")
    @ResponseBody
    String interceptorTest() {
        return "拦截器未开启";
    }

2.不开启拦截器,即把InterceptorTest.preHandle改为return true

SpringBoot配置拦截器

3.开启拦截器,即把InterceptorTest.preHandle改为return false

SpringBoot配置拦截器