应用:对于某些url 执行拦截 验证。
- 1、书写 HandlerInteceptor 的实现类
Intercept the execution of a handler. Called after HandlerMapping determined an appropriate handler object, but before HandlerAdapter invokes the handler.DispatcherServlet processes a handler in an execution chain, consisting of any number of interceptors, with the handler itself at the end.With this method, each interceptor can decide to abort the execution chain,typically sending an HTTP error or writing a custom response.
@Slf4j
public class TestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("########请求URI为{}",request.getRequestURI());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
}
- 2、将该实现类注册进InterceptorRegistry
方式:
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
所以 我们应该书写自己的配置类 @Configuration 同时实现 WebMvcConfigur或者如下 定义组件并被容器管理
@Configuration
public class MyConfig {
/**
* 定制spring mvc
* @return
*/
@Bean
public WebMvcConfigurer getWebMvcConfigurer (){
WebMvcConfigurer webMvcConfigurer = new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
}
};
return webMvcConfigurer;
}
}