SpringBoot拦截器的使用

时间:2021-03-16 23:20:16

一、首先建立拦截器,继承HandlerInterceptor

public class CustomInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
MsgUtils.println("自定义拦截器->执行之前");
return true;
}

@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
MsgUtils.println("自定义拦截器->执行之后");
}

@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}

或者继承HandlerInterceptorAdapter,选择实现其中的方法

public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MsgUtils.println("自定义拦截器-适配器模式->执行之前");
return true;
}
}

二、设置添加拦截器

@Configuration
public class WebmvcConfig extends WebMvcConfigurerAdapter {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/**");
}

}

好了,测试一下:

SpringBoot拦截器的使用

成功执行。多个拦截器的执行顺序跟添加顺序一致。