springboot中定义拦截器


 

首先回忆一下springmvc中拦截器的使用:

1.定义一个类 implements HandlerInterceptor,实现HandlerInterceptor接口中的方法

  preHandler               1

  postHandler              2

  afterCompletion        3

2.配置拦截器 springmvc.xml

<mvc:Interceptors>
  <mvc:Interceptor>
    <path="/user/*">
    <exinclud path="/user/login">
  </mvc:Interceptor>
</mvc:Interceptors>

springboot 中不建议使用xml文件,在使用拦截器的时候springboot框架自动配置

springboot中定义和使用拦截器如下:

1.开发自定义拦截器类

拦截器类 implements HandlerInterceptor

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("=======1=======");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("========2========");
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("==========3========");
    }
}

 

2.配置拦截器,springboot自动配置(@Configuration)

@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor())
                .addPathPatterns("/user/test")       //拦截项目中的哪些请求
                .excludePathPatterns("/user/save");  //对项目中的哪些请求不拦截
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM