在Spring Boot中使用拦截器

实现自定义拦截器步骤:

1.创建拦截器类并实现HandlerInterceptor接口;

2.创建类继承WebMvcConfigurationSupport,并重写addInterceptors方法;

3.在继承WebMvcConfigurationSupport类中实例化自定义的拦截器,将对象添加到拦截器链中(在addInterceptors方法中添加)。

创建拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class LoginInterceptor 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......");
}
}

添加拦截器

创建类MyInterceptorConfig并继承WebMvcConfigurationSupport,在addInterceptors方法中添加拦截规则:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
// 需添加此注解,否则拦截器无效
@Component
public class AdapterConfig extends WebMvcConfigurationSupport {
@Bean
LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
@Override
protected void addInterceptors(InterceptorRegistry registry) {
// 新增拦截规则
registry.addInterceptor(loginInterceptor()).addPathPatterns("/**");
// 设置不拦截url列表
registry.addInterceptor(loginInterceptor()).excludePathPatterns("/test");
super.addInterceptors(registry);
}
}

在以上代码中路径/test设置为不拦截,如果/test这个路径不存在或未定义路由,那么当你访问这个路径时依然会被拦截,因为此时变成了error这个路径。而如果使用普通的Spring MVC项目,访问/test路径不会被拦截,如果没有定义此路径或路由就会报404。