Dropwizard Add a response filter for all resources

How do I add a filter to my Dropwizard application that will check the response returned by each resource?

Should I use javax.servlet.Filterorjavax.ws.rs.container.ContainerResponseFilter

Any examples related to its use would be appreciated.

+4
source share
2 answers

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

  • 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() {
        }
    }
    
  • Then register the same on your own Service, which 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, "/*");
      }
    }
    
  • Now you should well filter all the resources using the one described above CustomFilter.

+2
source

I think you want to use 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 details here .

+1
source

Source: https://habr.com/ru/post/1686489/


All Articles