TechnoBuzz

A Techno Blog, mainly about Java

Servlet Filters

Servlet Filters [ link ] — are not Servlets and they are not responsible for
creating a response.

They are preprocessors of requests before they
reach a Servlet and postprocessors of responses after leaving a
Servlet.

Servlet filters can:

  • Intercept a Servlet’s invocation before the Servlet is called

  • Examine a request before the destination Servlet is invoked

  • Modify request headers and request/response data by subclassing the HttpServletRequest object and wrapping the original request

  • Intercept a Servlet’s invocation after the servlet is called

The designers of Servlet Filters identified the following examples for their use:
Authentication Filters, Logging and Auditing Filters,Image conversion Filters, Data compression Filters, Encryption Filters, Tokenizing Filters, Filters that trigger resource access events, XSL/T filters, Mime-type chain Filter

web.xml:

<filter>
      <filter-name>My Filter</filter-name>
      <filter-class>com.myproject.MyFilter</filter-class>
      <init-param>
         <param-name>enable</param-name>
         <param-value>yes</param-value>
      </init-param>
</filter>

<filter-mapping>
      <filter-name>My Filter</filter-name>
      <servlet-name>action</servlet-name>
</filter-mapping>

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
public class MyFilter implements Filter
{
    boolean _enable = false;

    public void init(FilterConfig fc) throws ServletException
    {
        String enable=fc.getInitParameter("enable");
        if ("yes".equals(enable))
            _enable=true
    }
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                  throws IOException, ServletException
    {
        HttpServletRequest  request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
       
        if (! _enable)
        { // proceed with request
            chain.doFilter(request, response);
            return;
        }
       doIt();
        chain.doFilter(request, response);
        //After
FilterChain.doFilter() returns, the filter can do more processing if it
chooses;      
        doINextt();
}

public void destroy()
    {
    }
}

 

Advertisements

November 5, 2006 - Posted by | Web Design

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: