SpringBoot配置拦截器
1.实现一个拦截器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 实现HandlerInterceptor 重写preHandle方法,postHandler,afterCompletion方法 public class testInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("进入拦截器啦!"); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { System.out.println("Bye!"); }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("执行了TestInterceptor的afterCompletion方法"); } }
|
2.将拦截器配置到SpringBoot程序中,在Spring中,使用XML的方式,而在Boot中只需要定义一个带有@Configuration的配置类即可,需要实现WebMvcConfigure接口
1 2 3 4 5 6 7 8 9 10 11 12
| @Configuration public class testMvcConfigure implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration registration = registry.addInterceptor(new testInterceptor()); registration.addPathPatterns("/**"); registration.excludePathPatterns( "/vip/wang" ); }
}
|