在Spring Boot中使用HandlerInterceptor的步骤如下:
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 在请求处理之前进行调用(Controller方法调用之前) return true; // 返回true表示继续执行后续的拦截器和Controller方法,返回false表示终止执行 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 整个请求处理完毕后进行调用,即在视图渲染完毕或者调用方已经拿到响应数据之后 } } 在配置类上添加@EnableWebMvc注解,开启Spring MVC的配置。
创建一个继承WebMvcConfigurerAdapter的配置类,并重写addInterceptors方法。在该方法中添加自定义的拦截器。
@Configuration @EnableWebMvc public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); // 添加拦截路径 } } @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Configuration @EnableWebMvc public static class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } } } 这样就完成了HandlerInterceptor的配置和使用。自定义的拦截器会在请求处理前、请求处理后和整个请求处理完毕后进行调用。可以在拦截器中添加一些自定义的逻辑,例如身份验证、日志记录等。