首先回忆一下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"); //对项目中的哪些请求不拦截 } }