SpringBoot实战之5 注册interceptor

前言

HandleInterceptor的功能跟Filter类似,但是范围要小一些,只拦截webmvc的接口请求,不拦截静态资源。即request请求之前有拦截方法,request请求之后有拦截方法。

实现方法

实现自定义拦截器需要3步:

1、创建我们自己的拦截器类并实现 HandlerInterceptor 接口。

2、创建一个Java类继承WebMvcConfigurerAdapter,并重写 addInterceptors 方法。

3、实例化我们自定义的拦截器,然后将对像手动添加到拦截器链中(在addInterceptors方法中添加)

code实现

MyInterceptor1.java

public class MyInterceptor1 implements HandlerInterceptor{
    private final Logger _logger = LoggerFactory.getLogger(this.getClass()) ;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        _logger.info("this is MyInterceptor1 preHandle");
        // 只有返回true才会继续向下执行,返回false取消当前请求
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        _logger.info("this is MyInterceptor1 postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        _logger.info("this is MyInterceptor1 afterCompletion");
    }
}

MyInterceptor2.java

public class MyInterceptor2 implements HandlerInterceptor{
    private final Logger _logger = LoggerFactory.getLogger(this.getClass()) ;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        _logger.info("this is MyInterceptor2 preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        _logger.info("this is MyInterceptor2 postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        _logger.info("this is MyInterceptor2 afterCompletion");
    }
}

注册Interceptor拦截器链

@Configuration
public class MyInterceptorConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor1()).addPathPatterns("/**");
        registry.addInterceptor(new MyInterceptor2()).addPathPatterns("/**");
        super.addInterceptors(registry);
    }
}

程序入口

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

源码

springboot-interceptor

历史文章

SpringBoot实战之入门

springboot实战之文章汇总

springboot实战之读取配置文件

springboot实战之整合jsp模版引擎

springboot实战之整合freemarker模版引擎

springboot实战之注册自定义Servlet

springboot实战之注册filter和listener

你可能感兴趣的:(springboot实战,interceptor,springboot)