Sunday 2 May 2010

Filter

Introduction:
·         As we know that how to manage session (Session management, HttpSession) in web application.
·         And if we want to make sure that a resource( jsp, servlet, etc) is accessible only when user session is valid, we can achieve this by using servlet session attributes.
·         But if we have a huge number of servlets and jsps, then it will become hard to maintain because of redundant(repeated) code.
If we want to change the attribute name in future, we will have to change all the places where we have session authentication.

What is Servlet Filter?
It is an Interface which is predefined in javax.servlet.Filter interface
A Servlet filter is an object that can intercept(stops) HTTP requests targeted at your web application. 
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content
By using the Servlet Filter class we can overcome the following problems:


Some common tasks that we can do with filters are:
·         Logging request parameters to log files.
·         Authentication and autherization of request for resources.
·         Formatting of request body or header before sending it to servlet.
Internationalization
·         Compressing the response data sent to the client.
Alter response by adding some cookies, header information etc.

Purpose of Servlet Filter

Intercept request from a client browser before it gets processed in the server
Intercept/manipulate response from server before it is sent to the client browser


Advantages of Servlet Filter

Servlet filter is pluggable
No dependency between filters
 




following diagram illustrates:



Servlets and filters both are unaware of each other and we can add or remove a filter just by editing web.xml.

We can have multiple filters for a single resource and we can create a chain of filters for a single resource in web.xml. We can create a Servlet Filter by implementing javax.servlet.Filter interface.
For more information http://docs.oracle.com/javaee/6/api/javax/servlet/Filter.html
Advantages of Filters:

  • Reusable code : that can transform the content of requests, responses, and header information from one format to another: Example: a web application that formats the data before it is presented to the client. And different clients require different formats such as Wireless Markup Language(WML), Excel Sheets, Portable Document Format(PDF) to do this we need of transformation of filtering in a Web application.
Work flow of Filter:
·         When the web container loads the filter class using the normal java class loading
·         This class may be loaded from a local file system, a remote file system, or other network services
·         If the web container fails to load the class, it terminates this initialization process.
·         After the filter class is loaded, the web container creates the object of Filter class. The Web container uses the no-argument constructor to create a new instance of the Filter class.
·         Once the Filter object is created, the web container initializes the Filter object by invoking init(0 and passing the FilterConfig object reference to this method.
·         FilterConfig object allows the Filter object to access name-value configured initialization parameters, the reference to the ServletContext interface for the Web Application, and other container specific details.
·         The Web Container creates one FilterConfig object per filter declaration in the deployment descriptor.
·         The init() reads the configuration data and initialize resources, then the Web container keeps the Filter object into active state that is it makes it available and ready to handle requests, Otherwise, if the filter fails to initialize, it throws the UnavailableException. If the init(0 of Filter interface throws an exception, the Web container does not put this object into the active state. That is it removes the object.
·         After deploying the web application or before the request is sent to the Web container to access a Web resource, the container locates the list of filters that must be applied to the Web resource.
·         When the container receives the request, it takes the first filter object from the list and calls its doFilter() method passing ServletRequest, ServletResponse and a reference of the FilterChain object that it uses.
·         The doFilter() method of a Filter performs preprocessing, such as examining the request’s headers, wrapping the request and / or response object passed into its doFilter() method with a customized implementation of ServletRequest, or HttpServletRequest and / or ServletResponse or HttpServletResponse respectively to modify request/response headers or data.
·         After performing all its preprocessing operations, if any, the filter may call doFilter() on FilterChain object passing in the request and response objects.
·         The doFilter() method of FilterChain is responsible to invoke the next entity in the chain.
·         The next entity may be another filter, or if the filter making the invocation is the last filter configured for this chain then the next entity is the target web resource.
·         Otherwise filter can block the request by not making the call to invoke the next entity, that is by not calling doFilter() on FilterChain object.
·         After doFilter() method invocation on theFilterChain object, filter can perform post processing operations.
·         The destroy() method is called either after all threads have completed their functionality or when thread’s timeout period elapses. This method detaches all resources such as memory and threads from filter instance.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
    <display-name>ServletFilter</display-name>
    <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.tech2money.HelloServlet</servlet-class>

    </servlet>
    <servlet-mapping>

        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/HelloServlet</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>HalloFilter</filter-name>

        <filter-class>com.tech2money.HalloFilter</filter-class>

    </filter>



    <filter-mapping>

        <filter-name>HalloFilter</filter-name>

        <url-pattern>/HelloServlet</url-pattern>

    </filter-mapping>


    <welcome-file-list>

        <welcome-file>index.jsp</welcome-file>

    </welcome-file-list>

</web-app>


Example of basic Servlet Filter class

package com.rajendra;
import javax.xml.crypto.dsig.spec.XPathType.Filter;
public class HalloFilter extends Filter {
/**
     * init() is called by the web container to indicate to a filter that it is being placed into service.

     * @param config

     * @throws ServletException

     */

    public void init(FilterConfig config) throws ServletException {

        // Get init parameter which is defined in the <init-param> tag in web.xml for filter definition

        String initParam = config.getInitParameter("init-Param");



        // Print the init parameter

        System.out.println("Init Param: " + initParam);

    }



    /**

     * doFilter() 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.

     * @param request

     * @param response

     * @param chain

     * @throws java.io.IOException

     * @throws ServletException

     */

    public void doFilter(ServletRequest request, ServletResponse response,
30
            FilterChain chain) throws java.io.IOException, ServletException {



        // Get the IP address of client machine.

        String ipAddress = request.getRemoteAddr();



        // Log the IP address and current timestamp.

        System.out.println("IP " + ipAddress + ", Time "+ new Date().toString());



        // Pass request back down the next resource

        chain.doFilter(request, response);

    }



    /**

     * destroy() is called by the web container to indicate to a

     * filter that it is being taken out of service.

     */

    public void destroy() {

        /*

         * Called before the Filter instance is removed from service by the web

         * container

         */

    }

}

No comments:

Post a Comment