按路径模式排除Spring请求HandlerInterceptor
我知道我们可以将不同的url映射到不同的拦截器,也可以将多个url映射到单个拦截器。我只是想知道我们是否也有排除选项。例如,如果我在应用程序中有50个url映射,除了1个映射之外,我想为所有这些调用侦听器,而不是为49个映射编写配置,那么我可以只提到*和一个排除到第50个url吗 可以对(多个)特定url或url模式应用或排除HandlerInterceptor 看 以下是文档中的示例按路径模式排除Spring请求HandlerInterceptor,spring,interceptor,Spring,Interceptor,我知道我们可以将不同的url映射到不同的拦截器,也可以将多个url映射到单个拦截器。我只是想知道我们是否也有排除选项。例如,如果我在应用程序中有50个url映射,除了1个映射之外,我想为所有这些调用侦听器,而不是为49个映射编写配置,那么我可以只提到*和一个排除到第50个url吗 可以对(多个)特定url或url模式应用或排除HandlerInterceptor 看 以下是文档中的示例 @Configuration @EnableWebMvc public class WebConfig ext
@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>
我认为在SpringBoot2.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
}
}
就我而言:
/api/v1/用户管理器服务/租户/添加
路径模式配置不正确:
@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/**");
}
为什么每个人都只是举个例子?我需要排除多个映射,而这个示例对我来说没有任何帮助。这一点很好。你有没有看过模式/方法签名?无论如何。更新了答案。