2017-08-22 7 views
1

のパターンを除外し、私は、上記正常に動作している管理者のパスパターン春ConfigurerAdapterがSpringBootアプリケーションでは、別のHTTPメソッド

@Configuration 
    public class CommsCoreWebConfig extends WebMvcConfigurerAdapter { 

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

    } 

を除くすべてのコントローラのコールのためにユーザを検証バリデータを持っている今、私は除外したいです/ contents/**という別のパスのユーザ検証はHEADメソッドだけであるが、GET、POST/contents/**のためにバリデータが呼び出されるようにしたい。

たちは

答えて

1

は、エンドポイント・パス上のバリデータを条件付きにするにはそれを行うことができる方法がHttpMethodあなたがバリデータに条件ロジックをそこに追加することができますです。あなたはInterceptorRegistryUserValidatorを登録しているので、それは...この例のようなので、何か...

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; 
    } 
} 

HandlerInterceptorにする必要がありますが、検証は両方HttpMethodとエンドポイントのパスに基づいて適用されているかどうかを制御することができるようになります。

+0

ありがとうございます@グリッチそれは動作します。私はこれがフレームワークに追加されるべきだと思う – Tatha

関連する問題