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.
Registering A Resource A Dropwizard application can contain many resource classes, each corresponding to its own URI pattern. Just add another @Path -annotated resource class and call register with an instance of the new class. Before we go too far, we should add a health check for our application.
Dropwizard uses Logback for its logging backend. It provides an slf4j implementation, and even routes all java. util. logging , Log4j, and Apache Commons Logging usage through Logback.
Bootstrap is the pre-start (temp) application environment, containing everything required to bootstrap a Dropwizard command. Here is a simplified code snippet to illustrate its structure: Bootstrap(application: Application<T>) { this. application = application; this. objectMapper = Jackson.
To add a response filter for all the resources using dropwizard 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 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, "/*");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With