环境说明
- spring boot 1.5.9
- jdk8
问题概述
在spring boot中使用Filter和HandlerIntercepter中对于相同路径匹配写法有差别,如路径/api/v1/service1
,在Filter中可以使用/api/*
,但在HandlerIntercepter注册时需要写成/api/**
,以下为相关具体说明
1. Filter
在spring boot中自定义Filter(该Filter继承自org.springframework.web.filter.OncePerRequestFilter
)在注册匹配路径时,对于/api/v1/service1
做路径映射时,需要使用/api/*
匹配
完整代码如下:
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
//初始化自定义RequestFilter
ApiRequestFilter apiRequestFilter = new ApiRequestFilter(apiConfigService);
registrationBean.setFilter(apiRequestFilter);
List<String> urlPatterns = new ArrayList<>();
//设置映射路径
urlPatterns.add("/api/*");
registrationBean.setUrlPatterns(urlPatterns);
return registrationBean;
}
2. HandlerInterceptor
在spring boot中自定义HandlerInterceptor(该HandlerInterceptor继承自org.springframework.web.servlet.handler.HandlerInterceptorAdapter
)在注册匹配路径时,对于/api/v1/service1
做路径映射时,需要使用/api/**
匹配
完整代码如下:
@SpringBootApplication
@RestController
public class DemoApplication extends WebMvcConfigurerAdapter {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器
registry.addInterceptor(new ApiInterceptor()).addPathPatterns("/api/**");
}
}