SpringBoot - 拦截器_04

配置拦截器

Spring Boot也只是集成了Spring MVC而已,所以拦截器的写法还是一样的。不一样的是Spring MVC的拦截器需要在xml文件中配置,而Spring Boot只需要在类上加@Component注解即可,这样当前拦截器才会被扫描到。

1. 创建自定义拦截器

  • 实现HandlerInterceptor,并重写三个方法
  • 在拦截器类上添加注解@Component 为注入配置类
@Component  //为后面的注入使用
public class MyInterceptor implements HandlerInterceptor{
    /**
     * 预处理回调方法,实现处理器的预处理
     * 返回值:true表示继续流程;false表示流程中断,不会继续调用其他的拦截器或处理器
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("拦截器生效");
        return true;
    }

    /**
     * 整个请求处理完毕回调方法,即在视图渲染完毕时回调,
     * 如性能监控中我们可以在此记录结束时间并输出消耗时间,
     * 还可以进行一些资源清理,类似于try-catch-finally中的finally,
     * 但仅调用处理器执行链中
     */
    @Override
    public  void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                 @Nullable Exception ex) throws Exception {
    }

    /**
     * 后处理回调方法,实现处理器(controller)的后处理,但在渲染视图之前
     * 此时我们可以通过modelAndView对模型数据进行处理或对视图进行处理
     */
    @Override
    public  void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                            @Nullable ModelAndView modelAndView) throws Exception {
    }
}

2. 新建一个配置类管理拦截器

  • 该类需要继承WebMvcConfigurationSupport ,重写addInterceptors方法
  • 在该类上添加@SpringBootConfiguration注解 目前(2.0.4.RELEASE版本)WebMvcConfigurerAdapter已过时,过时的这个只不过是个适配器(适配器模式),可以直接使用它所实现的那个接口 WebMvcConfigurer
  • 注入自定义拦截器
@SpringBootConfiguration
public class MyInterceptorConfig extends WebMvcConfigurationSupport{

    @Autowired
    private MyInterceptor myInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns 用于添加拦截规则,/**表示拦截所有请求
        // excludePathPatterns 用户排除拦截 excludePathPatterns("/login","/register") 添加不拦截的方法
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

请求一个方法,打印到控制台,打印到控制台,查看拦截器是否生效

da

猜你喜欢

转载自blog.csdn.net/weixin_44100514/article/details/86507840
今日推荐