Filters are part of Servlet API Since 2.3. Like a Servlet, a filter object is instantiated and managed by the Container and follows a life cycle that is similar to that of a Servlet. A Servlet has 4 stages as depicted below
- Instantiate.
- Initialize.
- Filter.
- destroy.
These stages are similar to a servlet's Instantiate, Initialize, Filter, destroy. The filter is used to pre-process the request and Post-processing the response. A Filter is a java object that performs the Filtering task on either the request to a resource or on the response from a resource or both.
Some of the Applications using Filter
- Authentication.
- Logging and Auditing Filters
- Image Conversion Filters.
- Data Compression Filters.
- Encryption and Decryption Filters.
Interfaces belong to Filters.
- Filter.
- FilterConfig.
- FilterChain.
All these interfaces are available in javax.Servlet Package
Filter
- A Filter is an interface.
- Every Filter must be inherited from this interface.
- It provides lifecycle methods
Methods
Method | Action performed |
---|
init(FilterConfig filterconfig) | Called by the web container to indicate to a filter that it is being placed into service |
doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) | It 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. |
destroy() | to indicate to a filter that is being out of service. |
Note:
- Filter information must be provide inside web.xml .
- Filter is mapped with one or more than one servlet.
File: web.xml
XML
<web-app >
<servlet>
<servlet-name>name</servlet-name>
<servlet-class>Servlet class name</servlet-class>
</servlet>
<filter>
<filter-name>name</filter-name>
<filter-class>Filter class name</filter-class>
</filter>
<filter-mapping>
<filter-name>name</filter-name>
<url-pattern>/name</url-pattern>
</filter-mapping>
<servlet-mapping>
<servlet-name>name</servlet-name>
<url-pattern>/url</url-pattern>
</servlet-mapping>
</web-app>
FilterChain
FilterChain is an interface, which is implemented by a servlet container. Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain to invoke the resource at the end of the chain.
Method: doFilter()
Causes the next Filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.
Return Type: Void
Parameters:
- HttpServletRequest request
- HttpServletResponse response
Syntax:
void doFilter(HttpServletRequest request, HttpServletResponse response)
We can Develop three types of filters as listed below as follows:
(1) Request Filter: Contain only pre-request Processing logic.
Example: Request count filter, Authentication filter, Authorization filter, Validation filter and etc.
(2) Response Filter: Contain only Post-response generation logic.
Example: Conversion filter, Compression filter and etc.
(3) Request-Response Filter: Contain both pre-request and post-response generation logic.
Example: Performance Test filter.
Implementation: Example of Filter
A. File: index.html
HTML
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<a href="servlet1">click here</a>
<form>
<body>
<html>
B. File: MyBlockFilter.java
Java
// Java Program to Illustrate MyBlockFilter
// Importing required classes
import java.io.IOException;
import java.io.PrintWriter;
// Importing all servlet classes
import javax.servlet.*;
// Class
// Implementing Filter class
public class MyBlockFilter implements Filter {
// Method
public void init(FilterConfig config)
throws ServletException
{
}
// Method
public void doFilter(ServletRequest req,
ServletResponse resp,
FilterChain fc)
throws IOException, ServletException
{
String ip = req.getRemoteAddr();
PrintWriter out = resp.getWriter();
if (ip.equals("127.0.0.1")) {
out.print(
",<h2>Your ip address is blocked ny this websites</h2>");
}
else {
fc.doFilter(req, resp);
}
}
// Method
public void destroy() {}
}
C. File: HelloServlet
Java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h2>Hello Client welcome to my Website...</h2>");
}
}
D. File: web.xml
XML
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyBlockFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
Output: If our PC IP address is "127.0.0.1" we cannot visit the website

Similar Reads
Servlet - Filter
A filter is an object that is used throughout the pre-and post-processing stages of a request. Filters are mostly used for filtering tasks such as server-side logging, authentication, and authorization, input validation, and so on. The servlet is pluggable, which means that the entry is specified in
3 min read
Servlet - FilterChain
A filter is an object that is used throughout the pre-and post-processing stages of a request. Conversion, logging, compression, encryption and decryption, input validation, and other filtering operations are commonly performed using it. Servlet Filter Chain We will learn how to correlate a chain of
5 min read
Java Servlets | Need of Filters
The need for implementing filters can be understood with the help of few examples Let's take example of a Web application that formats the data to be presented to clients in a specific format say Excel However, at a later point of time, the clients may require data in some other format, such as Hype
3 min read
Java Servlet Filter with Example
A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server, i.e., before and after the execution of a servlet for filtering the request. Filter API (or interface) includes some methods which help us in filtering requests. To understand the concept of Fil
4 min read
Servlet Container in Java
A Servlet Container is the critical component of the Java's web application architecture and providing an environment where the Java Servlets are the executed. Servlets are the Java programs that can be extend capabilities of the servers, often the used to create dynamic web content. The servlet con
8 min read
Servlet - FilterConfig
An object of FilterConfig is created by the web container for each filter. It can be used to read filter init parameters. Placed in web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the filter. So it is easier to manage the web application if a
3 min read
Java Stream API â Filters
In this article, we will learn Java Stream Filter API. We will cover, 1. How stream filter API works. 2. Filter by Object Properties. 3. Filter by Index. 4. Filter by custom Object properties. Stream Filter API Filter API takes a Predicate. The predicate is a Functional Interface. It takes an argume
5 min read
Attributes in Servlets | Java
An attribute in servlet is an object that can be set, get or removed by the following aspects Request Scope Application Scope Session Scope To pass the value from servlet to html/jsp files, setAttribute() method is called by the request object. setAttribute() method takes an input as an object which
3 min read
Filter Pattern in Java
Filter pattern or Criteria pattern is a design pattern that enables developers to filter a set of objects using different criteria and chaining them in a decoupled way through logical operations. Procedure: Create a class on which Criteria is to be applied.Create an interface for Criteria.Create con
5 min read
Introduction to Java Servlets
Java Servlet is a Java program that runs on a Java-enabled web server or application server. It handles client requests, processes them, and generates responses dynamically. Servlets are the backbone of many server-side Java applications due to their efficiency and scalability.Key Features:Servlets
7 min read