Spring MVC 拦截器配置(Java配置方式)
Spring MVC推荐使用Java配置方式注册拦截器,相比XML配置更加灵活和类型安全。
实现WebMvcConfigurer接口
Java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Autowired
private LogInterceptor logInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 配置拦截器
}
}
基本拦截器注册
Java
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册日志拦截器,拦截所有路径
registry.addInterceptor(logInterceptor)
.addPathPatterns("/**");
// 注册登录拦截器
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/api/**")
.excludePathPatterns("/api/login", "/api/register");
}
路径匹配规则
Java
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuthInterceptor())
// 添加拦截路径
.addPathPatterns("/**") // 拦截所有路径
.addPathPatterns("/api/**") // 拦截api下所有路径
.addPathPatterns("/user/*") // 拦截user下的一级路径
.addPathPatterns("/order/**/*.do") // 拦截多层路径
// 排除路径
.excludePathPatterns("/login") // 排除登录页
.excludePathPatterns("/register") // 排除注册页
.excludePathPatterns("/static/**") // 排除静态资源
.excludePathPatterns("/error") // 排除错误页
.excludePathPatterns("/*.html") // 排除html文件
.excludePathPatterns("/swagger-ui/**"); // 排除swagger
}
路径模式说明
| 模式 | 说明 | 示例 |
|---|---|---|
* | 匹配单级路径 | /user/* 匹配 /user/list,不匹配 /user/admin/list |
** | 匹配多级路径 | /api/** 匹配 /api/user 和 /api/user/list |
? | 匹配单个字符 | /user? 匹配 /user1,不匹配 /user12 |
配置拦截器执行顺序
Java
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 按注册顺序执行:先注册的拦截器preHandle先执行
registry.addInterceptor(interceptor1)
.addPathPatterns("/**")
.order(1); // order值越小,优先级越高
registry.addInterceptor(interceptor2)
.addPathPatterns("/**")
.order(2);
registry.addInterceptor(interceptor3)
.addPathPatterns("/**")
.order(3);
}
完整配置示例
Java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
public LogInterceptor logInterceptor() {
return new LogInterceptor();
}
@Bean
public AuthInterceptor authInterceptor() {
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 1. 日志拦截器 - 最先执行
registry.addInterceptor(logInterceptor())
.addPathPatterns("/**")
.order(1);
// 2. 认证拦截器 - 第二执行
registry.addInterceptor(authInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns(
"/api/auth/login",
"/api/auth/register",
"/api/auth/captcha",
"/api/public/**"
)
.order(2);
}
}
结合路径匹配器
Java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ApiInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns(
"/api/login",
"/api/logout",
"/api/captcha/**",
"/api/public/**"
)
.pathMatcher(new AntPathMatcher()); // 指定路径匹配器
}
}
Spring Boot自动配置
Spring Boot中可直接注入拦截器:
Java
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final List<HandlerInterceptor> interceptors;
@Autowired
public WebConfig(List<HandlerInterceptor> interceptors) {
this.interceptors = interceptors;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
interceptors.forEach(interceptor -> {
registry.addInterceptor(interceptor)
.addPathPatterns(interceptor.getIncludePatterns())
.excludePathPatterns(interceptor.getExcludePatterns());
});
}
}
拦截器注解式配置
使用自定义注解标记需要拦截的方法:
Java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireAuth {
String value() default "";
}
// 拦截器实现
public class AuthInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
RequireAuth annotation = handlerMethod.getMethodAnnotation(RequireAuth.class);
if (annotation != null) {
// 检查登录状态
String token = request.getHeader("Authorization");
if (token == null) {
throw new UnauthorizedException("未授权访问");
}
}
}
return true;
}
}
常见排除路径配置
Java
private static final String[] EXCLUDE_PATHS = {
"/",
"/login",
"/register",
"/logout",
"/favicon.ico",
"/error",
"/static/**",
"/public/**",
"/swagger-ui/**",
"/swagger-resources/**",
"/v2/api-docs",
"/v3/api-docs/**",
"/webjars/**",
"/*.html",
"/*.css",
"/*.js",
"/*.png",
"/*.jpg",
"/*.gif"
};
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor())
.addPathPatterns("/**")
.excludePathPatterns(EXCLUDE_PATHS);
}
排除路径应包含所有静态资源和公开接口,避免不必要的拦截。
要点总结
- 实现WebMvcConfigurer接口,重写addInterceptors方法
- addPathPatterns指定拦截路径,excludePathPatterns排除路径
- order()方法控制拦截器执行顺序,值越小优先级越高
**匹配多级路径,*匹配单级路径- 生产环境需排除静态资源和公开接口
📝 发现内容有误?点击此处直接编辑