ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Writing Servlet 2.3 Filters
Pages: 1, 2, 3, 4

After writing the filters, they need to be defined and mapped to a URL pattern in the deployment descriptor. The order in which they are defined matters. The container will execute the filters in the order in which they are defined. Listing 5 shows the web.xml file for deploying Filter1.java and Filter2.java.


Listing 5: The deployment descriptor for the filter chaining. (web.xml)



<?xml version = "1.0" encoding = "ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

  <!-- Define the filters within the Web Application -->

  <filter>
    <filter-name>
      First Filter in Chain
    </filter-name>
    <filter-class>
      com.filters.Filter1
    </filter-class>
  </filter>

  <filter>
    <filter-name>
      Second Filter in Chain
    </filter-name>
    <filter-class>
      com.filters.Filter2
    </filter-class>
  </filter>


  <!-- Map the filter to a Servlet or URL -->

  <filter-mapping>
    <filter-name>
      First Filter in Chain
    </filter-name>
    <url-pattern>
      /simple
    </url-pattern>
  </filter-mapping>

  <filter-mapping>
    <filter-name>
      Second Filter in Chain
    </filter-name>
    <url-pattern>
      /simple
    </url-pattern>
  </filter-mapping>


  <!-- Define the Servlets within the Web Application -->

  <servlet>
    <servlet-name>
      Simple Servlet
    </servlet-name>
    <servlet-class>
      com.servlets.SimpleServlet
    </servlet-class>
  </servlet>


  <!-- Define Servlet mappings to urls -->

  <servlet-mapping>
    <servlet-name>
      Simple Servlet
    </servlet-name>
    <url-pattern>
      /simple
    </url-pattern>
  </servlet-mapping>

</web-app>


The output of the messages in the console is shown in Figure 5. Notice the request went through Filter1 and then Filter2, but the response went through Filter2 and then Filter1.

Screen shot.
Figure 5. Output from the filter chain.

Parsing a User's Request and Using Initial Parameters

So far the examples of the filters have been trivial. Now it's time to do something more realistic. Sometimes you may want to use a filter to verify certain objects pass with the requests, such as elements from an HTML form. You may want to verify the existence and validity of the values. If they don't exist, you send the client's request to one servlet. If they do exist but the values are not valid, then they are sent to a different servlet. Finally, if the elements check out, they are passed to the requested servlet. Figure 6 shows a diagram of this scenario.

Diagram of filtering the request.
Figure 6. Filtering a user's request and verifying HTML form data

Let's take this example one step further. Not only do we want to verify HTML form data, we want to retrieve the names of the HTML form elements from initialization parameters. This means that if the HTML form changes, we do not need to change any code in the filter; we simply change the initialization parameters for the filter.

Initialization parameters can be specified in the deployment descriptor. They are specified when the filter is defined. Listing 6 is the code for the filter that retrieves HTML form element names from initialization parameters, verifies the form data, and sends the request to the appropriate servlet.


Listing 6: A filter that verifies HTML form data. (RequestFilter.java)

package com.filters;

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

import java.util.Enumeration;

import java.io.IOException;
import javax.servlet.ServletException;

public class RequestFilter implements Filter
{
  private FilterConfig filterConfig;

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

    RequestDispatcher rd = null;
    boolean emptyform = false;

    try
    {

      Enumeration initParams = filterConfig.getInitParameterNames();

      // no initial parameters so invoke next element in chain
      if (initParams == null)
      {
        System.out.println("No elements to verify");
        chain.doFilter(request, response);
      }

      // grab init param values and get the form elements
      else
      {
        while (initParams.hasMoreElements())
        {
          String name = (String) initParams.nextElement();
          String value = filterConfig.getInitParameter(name);

          String formElement = request.getParameter(value);

          // check to see if element exists (i.e. form was sent)
          if (formElement == null)
          {
            rd = request.getRequestDispatcher("/noform");
            rd.forward(request, response);
          }

          // check to see if elements are empty
          else if (formElement.equals(""))
          {
            emptyform = true;
          }
        }

        // a form element was empty
        if (emptyform)
        {
          rd = request.getRequestDispatcher("/emptyform");
          rd.forward(request, response);
        }

        // form was filled out properly
        else
        {
          chain.doFilter(request, response);
        }
      }
    }

    catch (IOException io)
    {
      System.out.println("IOException raised");
    }
    catch (ServletException se)
    {
      System.out.println("ServletException raised");
    }



  }

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

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


Pages: 1, 2, 3, 4

Next Pagearrow