Dropwizard为所有资源添加响应过滤器

时间:2017-09-27 15:03:40

标签: java dropwizard

如何在我的 Dropwizard 应用程序中添加一个过滤器,以验证每个资源返回的响应?

我应该使用javax.servlet.Filter还是javax.ws.rs.container.ContainerResponseFilter

任何与其用途相关的例子都将受到赞赏。

2 个答案:

答案 0 :(得分:4)

要使用为所有资源添加响应过滤器,您可以执行以下操作:

  1. 创建一个扩展url -

    的CustomFilter
    javax.servlet.Filter
  2. 然后将其注册到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() { } } 扩展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过滤所有资源。

答案 1 :(得分: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