Servlet Filters

A filter is a Java class that is invoked in response to a request for a resource in a Web application. Resources include Java servlets, JavaServer pages (JSP), and static resources such as HTML pages or images. A filter intercepts the request and can examine and modify the response and request objects or execute other tasks.

In other words,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.
Filters are an advanced Java EE feature primarily intended for situations where the developer cannot change the coding of an existing resource and needs to modify the behavior of that resource In some situations, using filters can add unnecessary complexity to an application and degrade performance

How Filters Work

A filter intercepts a request for a specific named resource or a group of resources (based on a URL pattern) and executes the code in the filter. For each resource or group of resources, you can specify a single filter or multiple filters that are invoked in a specific order, called a chain.
When the servlet container calls a method in a servlet on behalf of the client, the HTTP request that the client sent is, by default, passed directly to the servlet. The response that the servlet generates is, by default, passed directly back to the client, with its content unmodified by the container. In this scenario, the servlet must process the request and generate as much of the response as the application requires.
But there are many cases in which some preprocessing of the request for servlets would be useful. In addition, it is sometimes useful to modify the response from a class of servlets. A filter can encrypt the responses.
Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks.
A common scenario for a filter is one in which you want to apply preprocessing or postprocessing to requests or responses for a group of servlets, not just a single servlet.

Uses for Filters

1• Authentication Filters
2• Logging and Auditing Filters
3• Image conversion Filters
4• Data compression Filters
5• Encryption Filters
6• Tokenizing Filters
7• Filters that trigger resource access events
8• XSL/T filters
9• Mime-type chain Filter

Note that filters are not servlets. They do not implement and override HttpServlet methods such as doGet() or doPost(). Rather, a filter implements the methods of the javax.servlet.Filter interface. The methods are:

● init()
● destroy()
● doFilter()

Method NameMethod Summary
Called by the web container to indicate to a filter that it is being taken out of service.
voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)
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.
voidinit(FilterConfig filterConfig)
Called by the web container to indicate to a filter that it is being placed into service.

How the Servlet Container Invokes Filters

shows daigram how the servlet container invokes filters. On the left is a scenario in which no filters are configured for the servlet being called. On the right, several filters (1, 2, ..., N) have been configured in a chain to be invoked by the container before the servlet is called and after it has responded. The web.xml file specifies which servlets cause the container to invoke the filters.

Servlet Filters

The order in which filters are invoked depends on the order in which they are configured in the web.xml file. The first filter in web.xml is the first one invoked during the request, and the last filter in web.xml is the first one invoked during the response. Note the reverse order during the response.

Filtering of Forward or Include Targets

In the OC4J 10.1.2 implementation, when a servlet is filtered, any servlets that are forwarded to or included from the filtered servlet are not filtered by default. You can change this behavior, however, through the following environment setting:


This flag is set to false by default.

Filter Examples

package com.example.filter;
import javax.servlet.*;

public class MyGenericFilter implements javax.servlet.Filter {
  public FilterConfig filterConfig;                                 

  public void doFilter(final ServletRequest request,               
                       final ServletResponse response,
                       FilterChain chain)
      throws, javax.servlet.ServletException { 

  public void init(final FilterConfig filterConfig) {               
    this.filterConfig = filterConfig;

  public void destroy() {                                           

Save this code in a file called in the package directory. The numbered code notes refer to the following:

● This code declares a variable to save the filter configuration object.
● The doFilter() method contains the code that implements the filter.
● In the generic case, just call the filter chain.
● The init() method saves the filter configuration in a variable.
● The destroy() method can be overridden to accomplish any required finalization.

References : oracle | oracle| oracle

share on :        :  

Love to hear your Views / Guidance / Recommendations on this Post…

Explore the Technology World

Computer Programming Terminologies Computer Programming Terminology is a general word for the group of specialized words or meanings relating to Computer Programming, and also the study of such t ...Read MoreNew features in JDK 12 with IntelliJ IDEADeveloped by JetBrains (formerly known as IntelliJ) ,IntelliJ IDEA is a Java integrated development environment (IDE) for developing computer software. It is av ...Read MoreGoogle Pay API Implementation Demo for AndroidIn this youtube Channel by Android Developers ,Learn how to implement the Google Pay API for Android with just a few lines of code and how it works with your ex ...Read MoreUnit Testing in .NET Core and Azure Devops pipelineUnit testing is a software testing method by which individual units of source code, usage procedures,sets of one or more computer program modules together with ...Read MoreThe mind behind Linux & GIT : Linus TorvaldsLinus Torvalds transformed technology twice — first with the Linux kernel, which helps power the Internet, and again with Git, the source code management ...Read MoreTensorflow and deep learningWith Tensorflow ,deep machine learning transitions from an area of research into mainstream software engineering. ...Read MoreJava program to return all possible permutations from collection of distinct numbersexample of Java program to return all possible permutations from collection of distinct numbers ...Read MoreReal Time Analytics with Spring Application Development FrameworkSpring is the most popular application development framework for enterprise Java.Millions of developers use Spring to build simple, truly portable, fast and fle ...Read MorePath Setting in Java When an application is launched from command prompt Windows OS searches for the executable program in the current working directory. The prompt throws an error ...Read MoreFacebook | whatsapp|Github | Twitter | LinkedIn | Youtube| reddit About | Cookies-Policy | Disclaimer | Site Map | Contact

Call / Visit for New Batch


Why Join Us

  • ➯ Free Demo Classes
  • ➯ No Registration Fee
  • ➯ Interview Questions
  • ➯ Study Materials
  • ➯ Softwares
  • ➯ Aptitude & Reasoning
  • ➯ Placement Assitance


  • MyJava Training Institute ,
  • Plot No.243 , shop No 14 ,
  • Secnd Floor , Zone-II ,
  • M.P.Nagar , Bhopal,
  • Madhya Pradesh ( 462011 )
  • ☎  08871209400 , 7987028543
  • 🌐
FacebookGoogle +TwitterYouTube

MyJava - java Training Institute