【问题标题】:Spring ConfigurerAdapter exclude Pattern for separate http methodSpring ConfigurerAdapter 为单独的 http 方法排除模式
【发布时间】:2018-01-31 05:01:16
【问题描述】:

在 SpringBoot 应用程序中,我有一个验证器,它为每个控制器调用验证用户,除了管理路径模式

    @Configuration
    public class CommsCoreWebConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new UserValidator()).addPathPatterns("/**").excludePathPatterns("/admin/**");
        }

    }

以上工作正常,现在我想排除另一个路径的用户验证,例如 /contents/** 但仅适用于 HEAD 方法,我仍然希望为 GET、POST /contents/** 调用验证器。

有没有办法做到这一点

【问题讨论】:

    标签: spring spring-mvc spring-boot


    【解决方案1】:

    要使验证器以端点路径 HttpMethod 为条件,您可以向验证器添加条件逻辑。由于您使用InterceptorRegistry 注册UserValidator,那么它必须是HandlerInterceptor,所以类似于这个例子......

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    public class UserValidator extends HandlerInterceptorAdapter {
    
        @Override
        public boolean preHandle(HttpServletRequest request,
            HttpServletResponse response, Object handler) throws Exception {
            String path = antPathMatcher.extractPathWithinPattern(
                (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE),
                request.getPathInfo()
            );
    
            if (isExcluded(path, request.getMethod())) {
                // skip the validation
            } else {
               // do whatever your UserValidator usually does
            }
    
            return super.preHandle(request, response, handler);
        }
    
        private boolean isExcluded(String path, String requestMethod) {
            boolean isHeadMethod = HttpMethod.HEAD.matches(requestMethod);
            boolean isExcludedPath = EXCLUDED_PATHS.contains(path);
            return isHeadMethod && isExcludedPath;
        }
    }
    

    .. 将允许您控制是否基于 HttpMethod 和端点路径应用验证。

    【讨论】:

    • 感谢@glitch 它确实有效。我认为这应该添加到框架中
    猜你喜欢
    • 2015-05-19
    • 2011-11-01
    • 2017-01-28
    • 2012-12-02
    • 2020-04-03
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多