SpringBoot拦截器配置
SpringBoot可以通过实现WebMvcConfigurer
并添加@Configuration
注解来实现自定义部分SpringMVC配置。
1. 定义一个拦截器
@Slf4j // lombok
public class DemoInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("preHandle method running...");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle method running...");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion method running...");
}
}
2. 定义配置类,注册拦截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
/**
* 通过重写接口中的addInterceptors方法,添加自定义拦截器,并通过addPathPatterns方法指定拦截路径
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new DemoInterceptor()).addPathPatterns("/**");
}
}