Dropwizard Add Response Filter for All Resources

Viewed 2430

How can I add a filter to my Dropwizard application that will validate the response that every resource is returning?

Should I use javax.servlet.Filter or javax.ws.rs.container.ContainerResponseFilter

Any examples pertaining to its uses would be appreciated.

2 Answers

To add a response filter for all the resources using you can do the following :

  1. Create a CustomFilter that extends javax.servlet.Filter -

    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. Then register the same to your Service that extends 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. You should now be good to be filtering all the resources using the CustomFilter defined above.

I think what you want to use is 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.

More info here.

Related