Tutorial
Menus

Servlet - Advanced Servlet

Servlet Filter

Rating: 5.0/5 (3 votes cast)

Level   : Intermediate
Author : Arunkumar S
Download Source : filter.zip

Servlet Filter Tutorial (javax.servlet.Filter)

A filter is an object that can transform the header or content or both of a request or response. Filters differ from Web components in that they usually do not themselves create a response. Instead, a filter provides functionality that can be "attached" to any kind of Web resource. As a consequence, a filter should not have any dependencies on a Web resource for which it is acting as a filter so that it can be composable with more than one type of Web resource. The main tasks that a filter can perform are as follows:

    * Query the request and act accordingly.
    * Block the request-and-response pair from passing any further.
    * Modify the request headers and data. You do this by providing a customized version of the request.
    * Modify the response headers and data. You do this by providing a customized version of the response.
    * Interact with external resources.


You can configure a filter to act on a servlet or group of servlets. Zero or more filters can filter one or more servlets. A filter implements javax.servlet.Filter and defines its three methods:

   1. void init(FilterConfig config) throws ServletException: Called before the filter goes into service, and sets the filter's configuration object
   2. void destroy(): Called after the filter has been taken out of service
   3. void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException: Performs the actual filtering work



The server calls init(FilterConfig) once to prepare the filter for service, then calls doFilter() any number of times for requests specially set up to use the filter. The FilterConfig interface has methods to retrieve the filter's name, its init parameters, and the active servlet context. The server calls destroy() to indicate that the filter is being taken out of service. The filter lifecycle is now very similar to the servlet lifecycle -- a change recently made in the Servlet API 2.3 Public Final Draft #2. Previously the lifecycle involved a setFilterConfig(FilterConfig)method.

In its doFilter() method, each filter receives the current request and response, as well as a FilterChain containing the filters that still must be processed. In the doFilter()method, a filter may do what it wants with the request and response. (It could gather data by calling their methods, or wrap the objects to give them new behavior, as I'll discuss later.) The filter then calls chain.doFilter() to transfer control to the next filter. When that call returns, a filter can, at the end of its own doFilter() method, perform additional work on the response; for instance, it can log information about the response. If the filter wants to halt the request processing and gain full control of the response, it can intentionally not call the next filter.

Examples Filter with servlet
 
FirstFilter .java

package com.javaorigin.filter.example;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import java.io.IOException;
import javax.servlet.ServletException;
//@Author Arunkumar Subramaniam

public class FirstFilter implements Filter {
    private FilterConfig filterConfig;

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) {

        try {
            System.out.println("Filtering the Request..................");

            chain.doFilter(request, response);

            System.out.println("Filtering the Response..................");

        } catch (IOException io) {
            System.out.println("Exception from FirstFilter....."+io.getMessage());
        } catch (ServletException se) {
            System.out.println("Exception from FirstFilter....."+se.getMessage());
        }
    }

    public FilterConfig getFilterConfig() {
        return this.filterConfig;
    }

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

   
    public void destroy() {
   

    }

   
    public void init(FilterConfig arg0) throws ServletException {
   
    }
}
              

FirstServlet .java

package com.javaorigin.filter.example;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@Author Arunkumar Subramaniam

/**
 * Servlet implementation class for Servlet: FirstServlet
 *
 */
 public class FirstServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
  
   public FirstServlet() {
        super();
    }      
   
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request,response);
    }     
   
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doProcess(request,response);
    }                
   
    private void doProcess(HttpServletRequest request, HttpServletResponse response){
       
        System.out.println("This is Servlet.......................");
        System.out.println("www.javaorigin.com.......................");
       
       
    }
}


1 | 2 |  Next >

Discussion about this tutorial

  Start a new Discussion | Read All Discussion
Subject RepliesLast Post
Javaorigin.com contact@javaorigin.com