2017-09-27 3 views
4

Dropwizardアプリケーションにフィルタを追加して、すべてのリソースが返す応答を検証する方法を教えてください。Dropwizardすべてのリソースのレスポンスフィルタを追加

私はその用途に関係javax.servlet.Filterまたはjavax.ws.rs.container.ContainerResponseFilter

どれ例を使用すべきでいただければ幸いです。

答えて

2

次の操作を行うことができを使用して、すべてのリソースに対して応答フィルタを追加するには:

  1. javax.servlet.Filter拡張は、customFilter作成 - 次に

    public class CustomFilter implements Filter { 
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
         // your filtering task 
         chain.doFilter(req, res); 
        } 
    
        public void init(FilterConfig filterConfig) { 
        } 
    
        public void destroy() { 
        } 
    } 
    
  2. あなたServiceに同じを登録しますそれは延長するApplication -

    public class CustomService extends Application<CustomConfig> { //CustomConfig extend 'io.dropwizard.Configuration' 
    
        public static void main(String[] args) throws Exception { 
        new CustomService().run(args); 
        } 
    
        @Override 
        public void initialize(Bootstrap<CustomConfig> someConfigBootstrap) { 
        // do some initialization 
        } 
    
        @Override 
        public void run(CustomConfig config, io.dropwizard.setup.Environment environment) throws Exception { 
        ... // resource registration 
        environment.servlets().addFilter("Custom-Filter", CustomFilter.class) 
         .addMappingForUrlPatterns(java.util.EnumSet.allOf(javax.servlet.DispatcherType.class), true, "/*"); 
        } 
    } 
    
  3. 上記で定義したCustomFilterを使用してすべてのリソースをフィルタリングするのがよいはずです。

+0

これは私がやったことですが、リソースが完了した後にフィルタに到達する前にフィルタに入ることを続けます。 – Igor

+1

@Igorフィルタは、要求フィルタリングと応答フィルタリングの両方を対象としています。フィルタクラス内のコードは、何がフィルタリングされ、何に基づいて決定されるかを決定します。また、質問には、あなたが直面したエラーの内容が記載されていないため。 IMHOここで行ったように、設定の詳細を尋ねる代わりに、設定の詳細に直面したエラーのための別のスレッドが必要です。 :) – nullpointer

1

あなたが使いたいものはjavax.servlet.Filterだと思います。

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both.

詳細情報here

+0

私もそれについて考えましたが、あなたは例がありますか? – Igor

関連する問題