我知道我们可以将不同的url映射到不同的拦截器,或者我们也可以将多个url映射到单个拦截器。我只是想知道我们是否也有排除选项。例如,如果我在应用程序中有50个url映射,除了1个映射,我想为所有人调用拦截器,而不是为49映射编写配置,我可以提及*和一个排除到第50个URL吗?
答案 0 :(得分:17)
HandlerInterceptor
可以应用或排除到(多个)特定网址或网址模式。
请参阅MVC Interceptor Configuration。
以下是文档中的示例
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleInterceptor());
registry.addInterceptor(new ThemeInterceptor()).addPathPatterns("/**").excludePathPatterns("/admin/**");
// multiple urls (same is possible for `exludePathPatterns`)
registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/secure/*", "/admin/**", "/profile/**");
}
}
或使用XML配置
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/admin/**"/>
<bean class="org.springframework.web.servlet.theme.ThemeChangeInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<!-- intercept multiple urls -->
<mvc:mapping path="/secure/*"/>
<mvc:mapping path="/admin/**"/>
<mvc:mapping path="/profile/**"/>
<bean class="org.example.SecurityInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
答案 1 :(得分:1)
我认为在spring-boot 2.0版本中,这已经发生了很大变化。下面是您可以轻松添加和配置路径模式的实现。
@Component
public class ServiceRequestAppConfig implements WebMvcConfigurer {
@Autowired
ServiceRequestInterceptor sri;
@Override
public void addInterceptors(InterceptorRegistry registry) {
String pathPattern = "/admin/**";
registry.addInterceptor(sri).excludePathPatterns(pathPattern);
}
}
@Component
public class ServiceRequestInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// Your logic
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex){
// Some useful techniques
}
}
答案 2 :(得分:0)
就我而言:
/ api / v1 /用户管理器服务/租户/添加
PathPattern配置不正确:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/tenants/**");
}
我不见了:
/ **
在实际路径之前。
更正后,它可以按预期工作:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/**/tenants/**");
}