Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

Thursday, March 7, 2024

Difference between Servlet and Filter in Java

Servlet and Filter are two of the essential concepts defined in Servlet specification. They are core of any web application because most of the request will pass through them. This is why they are also very popular on Java Web developer interviews. What is the difference between a Servlet and a Filter is one of the most common and interesting interview question related to Servlet. If you can explain the difference clearly, you improve your chance of hiring a lot. In order to understand and explain the difference, you must understand what is the purpose of Servlet and Filter, How they work and how they are used in various web applications. 

A Servlet is nothing but a small Java program which runs inside web server. Servlet container create instance of Servlet and initialize it based upon configuration parameter provided in deployment descriptor and invokes it's service() method every time a request comes in. 

The server then process the request and send response usually across HTTP. The HttpServlet class, which is the most popular implementation of Servlet provides methods like doGet(), doPost() to handle different HTTP methods e.g. GET and POST. 

On the other hand Filter is an object which can intercept both request and response on their way and modify them. They can modify headers e.g. they can add additional headers or remove existing headers or they can modify response body e.g. an encryption filter can encrypt the response before sending or a compression filter can compress the response before sending to a client. 

Filters are really powerful and many frameworks uses Filter implementations for various things, and it's not uncommon to find custom implementations of them because they've very simple to write and useful. 

One of the best example of filters are Spring Security framework whose security implementation is totally based upon Filters. They have a chain of filters to perform various security related task e.g. authentication and authorization before handing over request to Servlet or response to Client. 


Similarities between Servlet and Filter

Before looking at the difference between a Servlet and a Filter, let's first see some similarities between them. Since both are defined in Servlet specification 2.3 and both are managed by Servlet container, it's obvious they are quite similar in nature too. 

1) Both are declared and defined in deployment descriptor file i.e. web.xml

2) Life-cycle of both Servlet and Filter is managed by Web Container. It is responsible for creating filter object, initializing it by calling init() method, calling doFilter() for filtering and destroy() method to destroy the Filter instance. Similarly, for Servlet also, container calls init(), service() and destroy() methods. 

3) Both Servlet and Filter has access to ServletRequest and ServletResponse objects. 

4) Both can be configured by providing init-param from web.xml. In case of Filter, FilterConfig object wrap those data and in case of Servlet, the ServletConfig wrap those data. 


Difference between a Filter and a Servlet

Now that you know what is a Servlet and a Filter and how they work, and you have also seen some similarities between them, it's the time to understand some key difference between a Servlet and a Filter in Java web application. Let's start with their purpose first. 

1. Purpose
The first and foremost difference between a Servlet and a Filter is their purpose, Filter is for pre-processing and post-processing request, while Servlet is for processing the request. 

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. 

While, A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.


2. Response
Filter don't generate response but they can modify response. It's Servlet's job to generate response. 

3. Chaining
Both Filter and Servlet have access to ServletRequest and ServletResponse object but only filter has access to FilterChain object, which means you can chain multiple filters for an ordered processing. 

One of the best example of chaining filter is Spring security's "security chain filter" which contains a stack of filter to apply various security concerns e.g. authentication and authorization. 

Difference between Servlet and Filter in Java


The filter chain is formed indirectly via filter mappings. The order of the filters in the chain is the same as the order that filter mappings appear in the web application deployment descriptor.

For example in following web.xml 
?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web 
Application 2.3//EN" "https://bit.ly/15eRp2z">
<web-app>
	<filter>
		<filter-name>jsonFilter</filter-name>
		<filter-class>JSONFilter</filter-class>
	</filter>
	<filter>
		<filter-name>analyticsFilter</filter-name>
		<filter-class>AnalyticsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>AnalyticsFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>JSONFilter</filter-name>
		<servlet-name>FilteredFileServlet</servlet-name>
	</filter-mapping>
	<servlet>
		<servlet-name>FilteredFileServlet</servlet-name>
		<servlet-class>FileServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>FilteredFileServlet</servlet-name>
		<url-pattern>/ffs</url-pattern>
	</servlet-mapping>
</web-app>

In this chain, first request is passed to json filter and then analytics filter and then finally to Servlet. In order to call the doFilter() method of next filter in chain, just call FilterChain.doFilter() method. 

4. Declaration
Even though, both Servlet and Filter are declared inside deployment descriptor, separate tags are used for them. Servlets are declared using <servlet> and <servlet-mapping> tag while Filters are defined using <filter> and <filter-mapping> tags, as shown in below screenshot.


5. Request Processing
Servlet has service() method to process the request while Filter has doFilter() method, but both methods are called by web container when a request comes in. The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

6. Request forwarding
A Servlet can forward a request to either another Servlet or a JSP, but a Filter can forward request to another Filter in the chain or to a Servlet only. 

7. Usage
The sole purpose of Servlet is to process request and generate response. The HttpServlet is used to generate a response as per HTTP protocol i.e. it contains HTTP headers and response body. On the other hand, Filter has been designed while keeping following usage in mind:
  • Authentication Filters
  • Logging and Auditing Filters
  • Image conversion Filters
  • Data compression Filters
  • Encryption Filters
  • Tokenizing Filters
  • Filters that trigger resource access events
  • XSL/T filters
  • Mime-type chain Filter

Spring security framework is a great example of what filter can do. It contains a suite of filters to carry out various security functionalities. 

Difference between Servlet and Filter in Java



8. Initialization
You can customize initialization of Servlet by using ServletConfig object and <init-param> tag in <servlet>, Similarly you can also customize initialization of Filter. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, and a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.

That's all about difference between Servlet and Filter in Java web application. Both are very useful and essential concepts and every Java web developer should be familiar with them. Just remember that it's Servlet who does the actual processing of request and responsible for generating response but you can decorate that response using Filter. 

You can do any kind of pre-processing and post-processing of HTTP request and HTTP response using Filter as they have access to both headers and body of request and response. Many cross cutting concerns on Web application e.g. logging, auditing, and security is implemented using Filters.

1 comment :

Anonymous said...

Very good article, now you are back to track, I loved when you write article like this, thanks

Post a Comment