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
voiddestroy()
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:

oracle.j2ee.filter.on.dispatch=true


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 java.io.IOException, javax.servlet.ServletException { 
    chain.doFilter(request,response);                                
  } 

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

  public void destroy() {                                           
  }
}

Save this code in a file called MyGenericFilter.java 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…

More Programming Topics

Key Features of the Java LanguageJava is simpler than most other languages that are used to create server applications because of its consistent enforcement of the object model.Introduction To JavaThe following sections explain how Java technology is both a programming language and a platform and provide an overview of what this technology can do for youChaining Constructor using SuperIf a subclass constructor invokes a constructor of its superclass either explicitly or implicitly there will be a whole chain of constructors called all the way back to the constructor of Object.Multilevel Inheritance in JavaMultilevel Inheritance is said to have taken place when a child class inherits from a parent class and then child class becomes the parent class for another class.Interface Inheritance JavaAn Interface declaration consists of modifiers the keyword interface the interface name a comma separated list of parent interfaces and the interface body.Inheritance in JavaA class that is derived from another class is called a subclass. The class from which the subclass is derived is called a superclass. This process of inheriting properties from another class is called Inheritance.White Spaces in JavaWhite Space is a character in Java. A character satisfies to be a White Space if and only if it is a Unicode space character.Serialization and Deserialization JavaTo serialize an object means to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object.Implementations in Collection FrameworkImplementations are the data objects used to store collections, which implement the interfaces described in the Interfaces section.

Explore the Technology World

An introduction to YouTube's new designThe Challenge Facing YouTube’s Design and Interaction Team When They Launched the Redesign Two Years Ago Was How to Tie Together a Host of Products with Very Different Audiences and UsesSpace 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 interviewsBeyond Mobile Server Games with Visual Studio for MacYou know that Visual Studio for Mac does Xamarin, but do You know what Else? We'll take a look at using Visual Studio for Mac for Mobile, Web, Game, Server less and IoT Development, and Connecting them with .NET Standard 2.0An introduction to YouTube's new designhe Challenge Facing YouTube’s Design and Interaction Team When They Launched the Redesign Two Years Ago Was How to Tie Together a Host of Products with Very Different Audiences and UsesAndroid Oreo Safer Than EverProtecting you from harm’s way. Android Oreo is more Secure than Ever.With Google Play Protect Built in, You’ll have Peace of Mind in the Palm of Your Hands

Call / Visit for New Batch

Services

Why Join Us

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

Address

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

MyJava - java Training Institute