spring-boot 拦截器
1.构建拦截器
必须实现HandlerInterceptor接口,
接口包括afterCompletion(controller执行完毕执行的方法)方法,preHandle(controller执行前执行的方法),postHandle(controller执行前执行的方法)
@Component public class SelfInterceptor implements HandlerInterceptor { public ResourceAuthInterceptor(){ System.out.println("constuct"); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String path = request.getRequestURI(); System.out.println(path); HandlerMethod method = (HandlerMethod)handler; String mapping = method.getMethod().getAnnotation(RestController.class).value(); return true; } }
2.注册拦截器
@Configuration public class InterceptorConfig extends WebMvcConfigurerAdapter { @Autowired private SelfInterceptor interceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(interceptor).addPathPatterns("/**"); super.addInterceptors(registry); } }