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 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


      <filter-name>My Filter</filter-name>

      <filter-name>My Filter</filter-name>

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))
    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);
        chain.doFilter(request, response);
FilterChain.doFilter() returns, the filter can do more processing if it

public void destroy()


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: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: