Call for New Batch / Any Query / Demo Classes : ☎ 08871209400 , 7987028543 , Zone-2,M.P.Nagar,Bhopal

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…

Global Tech NewsTop Programing Index January 2018January Headline Programming Language C awarded Language of the Year 2017,language C appears to be the fastest grower of 2017 in the TIOBE index and thus is declared programming language of the yearProgramming languages used in most popular websitesThe most popular websites have in common that they are dynamic websites. Their development typically involves server side coding client side coding and database technologyTop 10 Computer Science Skills That Could Sharpen Non-Computer Science CareersWhat do design marketing, engineering and data analysis have in common Theyre all careers where employers increasingly demand computer science skills.Oracle Buys AconexCreates the Worlds Most Comprehensive Cloud Offering for Managing All Aspects of Construction ProjectsOracle Unveils Worlds First Autonomous Database CloudAlso Introduces Oracle Autonomous Data Warehouse Cloud that has Demonstrated Performance of 10x Faster at Half the Cost of AmazonRecent List and Rankings Of Top Programming LanguagesThe programming languages Kotlin and C seem to be the only candidates to become programming language of the year 2017. TIOBE will announce the winner of this award next monthProgramming Index for November 2017This index ranks programming languages on the basis of their popularity.October Rankings Of Top Programming LanguagesIn the Beginning of this year the Programming Language Swift Peaked at a Rating of 2.3% in the TIOBE index and Even Reached a top 10 position. But now it is back at Position 16 and Constantly Declining Month after Month. Until recently it was quite Common to Program Android apps in Java and iOS apps in Swift/Objective-CAutosizing TextViewsAndroid O and Support Lib 26 allow to the text size expand,for Best user Experience with Text, Material Design Recommends Using a Dynamic Type Instead of smaller type Sizes or Truncating Larger-Size TextUsing Fonts in AndroidIntroduce to Android O and Support Library 26 new ways of working with Fonts. now You can Bundle Fonts as Resources by Adding the Font File in the Res/Font Folder and use it like any Other Asset in XML Layouts, Styles or Programmatically via the TypefaceSpace Station Crew Member Discusses His First Days in Space with Minnesota StudentsAboard the International Space Station, Expedition 53 Flight Engineer Mark Vande Hei of NASA fielded questions about life and work on the orbital outpost during an in-flight educational event Sept. 18 with students from the Pine River-Backus schools in Pine River, MinnesotaSpace Station Crew Members Discuss Life in Space with the MediaAboard the International Space Station, Expedition 53 Flight Engineers Mark Vande Hei and Joe Acaba of NASA and Paolo Nespoli of the European Space Agency discussed life and work aboard the orbital complex in a pair of in-flight interviews Sept. 20 with KSTP-TV, Minneapolis and the Associated Press

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 +LinkedInTwitterYouTube

MyJava - java Training Institute