1. 创建一个SpringBoot Web项目
server.port=9013
server.servlet.context-path=/013-springboot-interceptor
2. 实现一个登录拦截器
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("------preHandle-----");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
3. 通过配置类注册拦截器
在项目中创建一个config包,创建一个配置类InterceptorConfig,并实现WebMvcConfigurer接口, 覆盖接口中的addInterceptors方法,并为该配置类添加@Configuration注解,标注此类为一个配置类,让Spring Boot 扫描到,这里的操作就相当于SpringMVC的注册拦截器 ,@Configuration就相当于一个applicationContext-mvc.xml
配置类等同于.xml配置
@Configuration //注册一个拦截器,相当于applicationContext-mvc.xml配置
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//定义需要拦截的路径
String[] addPathPatterns = {
"/springBoot/**"
};
//定义不需要拦截的路径
String[] excludePathPatterns = {
"/springBoot/login",
"/springBoot/register"
};
//链式编程
registry.addInterceptor(new LoginInterceptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns);
}
}