Table of contents
1.
Introduction
2.
About Dropwizard
3.
Dropwizard Filters
4.
Types of Dropwizard Filters
4.1.
Jersey Filters
4.2.
Servlet Filters
5.
Frequently Asked Questions
5.1.
What is the HTTP server used by the Dropwizard Microservices framework?
5.2.
What is the purpose of Dropwizard?
5.3.
Dropwizard runs on which server?
5.4.
Is Dropwizard free and open source?
5.5.
How do I use Dropwizard to launch the terminal?
6.
Conclusion
Last Updated: Mar 27, 2024
Hard

Dropwizard Filters

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hello Techies!

Dropwizard is a microservice that is getting popular because of the convenience and ease it provides to JAVA developers. Dropwizard has got many components to it. This blog mainly discusses the Dropwizard Filters.

Dropwizard Filters

About Dropwizard

Dropwizard is an open-source Java framework for quick REST API (Restful Application Programming Interface) development. Dropwizard is an ecosystem that includes all dependencies, like Jersey, Jackson, or Jetty, in a single package or as a distinct module. If you do not use Dropwizard, you will gather all dependencies, frequently leading to class loading troubles owing to version mismatches between multiple Java libraries. Dropwizard solves this problem by combining sound, mature libraries into a lightweight package that lets you focus on getting things done.

Dropwizard logo

Now that we know what Dropwizard is let’s learn about Dropwizard Commands.

Dropwizard Filters

When we work on projects, we face cases where we have to filter out the requests or modify them before they reach our Resources. This is exactly where Dropwizard Filters comes to use.

To put it simply, filters allow us to change the attributes of requests and answers, such as HTTP headers. Filters can be used both on the server and on the client.

Keep in mind that filters are always executed, whether or not the resource was identified.

Types of Dropwizard Filters

In this section, we discuss the types of filters used in Dropwizard. Dropwizard essentially has two types of filters: Jersey and ServletLet’s know about them in detail.

Types of filters

Jersey Filters

What is Jersey?

It is an open source, production-quality Java framework for constructing RESTful Web Services that supports JAX-RS APIs (Application Programming Interface) and acts as a JAX-RS (JSR 311 & JSR 339) Reference Implementation. It has its API that extends the JAX-RS toolkit with additional features and utilities to make RESTful service and client development more accessible.

Jersey provides a robust API for filters and interceptors that can be efficiently utilized in Dropwizard. Throwing a WebApplicationException will prevent the request from reaching your resources. Filters can also be used to change inbound requests or outgoing responses.

Let us try to understand this with the help of an example:

@Provider
public class DateNotSpecifiedFilter implements ContainerRequestFilter {
    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException 
    {
        String dateHeader = requestContext.getHeaderString(HttpHeaders.DATE);
        if (dateHeader == null) 
        {
            Exception cause = new IllegalArgumentException("Date Header is not specified");
            throw new WebApplicationException(cause, Response.Status.BAD_REQUEST);
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


The above code contains an example of a filter that checks the request for the “Date” header. If it finds that the Date Header is missing, the IllegalArgumentException is thrown with the message “Date Header is not specified.”

We can bound the filters dynamically to resource methods using the DynamicFeature.

@Provider
public class DateRequiredFeature implements DynamicFeature {
    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        if (resourceInfo.getResourceMethod().getAnnotation(DateRequired.class) != null) {
            context.register(DateNotSpecifiedFilter.class);
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


When an application is started, the DynamicFeature is called by the Jersey runtime. In the example given above, the feature looks for methods annotated with @DateRequired and applies the DateNotSpecified filter exclusively to those methods.

We can register a feature in our Application Class as follows:

environment.jersey().register(DateRequiredFeature.class);

Servlet Filters

We have another way to create the Dropwizard Filters, which is by creating Servlet Filters.They let you to register filters that apply to both servlet and resource requests. Jetty comes with a few pre-installed filters that may already meet your requirements.

Let us now learn how to create a Servlet Filter for our Dropwizard Application. The example we are going to see below is analogous to the example we discussed above while creating a Jersey Filter.

public class DateNotSpecifiedServletFilter implements javax.servlet.Filter 
{
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
    {
        if (request instanceof HttpServletRequest) 
        {
            String dateHeader = ((HttpServletRequest) request).getHeader(HttpHeaders.DATE);

            if (dateHeader != null) 
            {
            	// This signals that the request should pass this filter
                chain.doFilter(request, response); 
            } 
            else 
            {
                HttpServletResponse httpResponse = (HttpServletResponse) response;
                httpResponse.setStatus(HttpStatus.BAD_REQUEST_400);
                httpResponse.getWriter().print("Date Header was not specified");
            }
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


This servlet filter that we created can be registered in our Application Class by enclosing it in Filterholder. Then, we can add it to the application context along with a specification for which pathways it will be active on. Here's an illustration:

environment.servlets().addFilter("DateNotSpecifiedServletFilter", new DateNotSpecifiedServletFilter()).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
You can also try this code with Online Java Compiler
Run Code


As we saw, filters are really advantageous when it comes to filtering out requests according to our needs or even modify them. This is a very advantageous feature provided by Dropwizard for smooth working on complex projects.

Frequently Asked Questions

What is the HTTP server used by the Dropwizard Microservices framework?

Dropwizard's default framework for constructing RESTful web apps is Jersey, and for managing JSON formats, Jackson is the standard.

What is the purpose of Dropwizard?

Dropwizard is an open-source Java framework for creating high-performance RESTful web services quickly. It assembles several popular libraries to form a lightweight package. Its primary libraries are Jetty, Jersey, Jackson, JUnit, and Guava.

Dropwizard runs on which server?

Dropwizard embeds an extremely tuned HTTP server straight into your project using the Jetty HTTP framework.

Is Dropwizard free and open source?

Dropwizard is an open-source and free Java framework for creating high-performance, ops-friendly RESTful backends.

How do I use Dropwizard to launch the terminal?

On the main tab, give the configuration a name and specify the primary class. Add server configuration.yml to the program arguments text field on the arguments tab. To launch your Dropwizard application, click the run button or press Ctrl+F11.

Conclusion

We hope this blog gave you a deep understanding of how Dropwizard Filters work and what their types are. We discussed the two kinds of Dropwizard Filters: the jersey and servlet filters, with a detailed example of each. Finally, we moved to Frequently Asked Questions. If you want to know more about Dropwizard, refer to the following articles:

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Keep learning, Keep Growing!

Live masterclass