按路径模式排除 Spring Request HandlerInterceptor

Exclude Spring Request HandlerInterceptor by Path-Pattern

我知道我们可以将不同的 url 映射到不同的拦截器,或者我们也可以将多个 url 映射到单个拦截器。我只是想知道我们是否也有排除选项。例如,如果我在应用程序中有 50 个 url 映射,除了 1 个映射,我想为所有映射调用拦截器,而不是为 49 个映射编写配置,我可以只提到 * 和一个排除到第 50 个 url 吗?

HandlerInterceptor 可以应用于或排除(多个)特定的 url 或 url-patterns。

参见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>

我认为在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
    }

}

就我而言:

/api/v1/user-manager-service/tenants/add

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/**");
}