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…

Explore the Technology World

Real 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 MorePicture-in-Picture App for Android devices with Source CodePicture-in-Picture is a special type of multi-window mode mostly used for video playback for Android devices.Released under Apache License 2.0 , which means you ...Read Moreopen source free template for personal or company blogsLooking for perfect theme for personal or company blogs.Released under the MIT license, which means you can use this template for any purpose, even for commerci ...Read MoreHow to Build an App for the Google AssistantApps for the Google Assistant are the gateway for your users to engage with your services through Google Home, Android phones, iPhones.Watch here to build an as ...Read MoreIntroduction to AMP - Accelerated Mobile PagesAMP, short for Accelerated Mobile Pages, is new new open source initiative to make the mobile web awesome again.Watch Here the Introduction to AMP ...Read MoreFacebook |Google+ | Twitter | LinkedIn | Youtube About | Cookies-Policy | Disclaimer | Site Map | Contact

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