基本介绍
在 Spring Boot 项目中, 拦截器是开发中常用手段,要来做登陆验证、性能检查、日志
记录等。拦截器在springmvc中大家应该都是学过的,这里就不赘述了
使用步骤
- 编写一个拦截器实现 HandlerInterceptor 接口
- 拦截器注册到配置类中(实现 WebMvcConfigurer 的 addInterceptors)
- 指定拦截规则
下面是我创建的应该拦截器,实现了HandlerInterceptor接口
public class InterceptorA implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle被调用");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle被调用");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion被调用");
}
}
接下来就是在配置类中对拦截器进行注入以及规则的指定
@Configuration
public class WebConfig {
@Bean
public WebMvcConfigurer webMvcConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new InterceptorA()).addPathPatterns("/t1");
}
};
}
}
registry.addInterceptor会返回一个InterceptorRegistration
我们通过InterceptorRegistration来指定拦截器的规则
然后就可以正常使用了,拦截器的用法和springmvc是一模一样的,这里就不再赘述