Servlet Filter

A filter is an object that is used to obstruct the request and response from server. It has a capability to change the response through Servlet or JSP page. Thus by using filter we can create reusable components.

Filter performs various filtering tasks such as compression, encryption, logging, authentication etc. From Servlet 3.0 we can use @WebFilter annotation instead of deploying the filter configurations in web.xml file.

The following interface is provided in javax.servlet package for performing filtering tasks:

  • Filter
  • FilterChain
  • FilterConfig

Filter Interface

Filter interface is implemented by servlet program to perform various filtering tasks. It provides three methods that must be required to override while implementing filter interface.

Methods provided by Filter interface.

  • public void init(FilterConfig con): Servlet container used this method to indicate that filter is ready to use. So before executing filtering tasks init() method is called. This method is invoked once in a lifetime of a servlet.
  • public void doFilter(ServletRequest req,ServletResponse res,FilterChain fc): This method works same as service() method in servlet. So the actual tasks are performed by doFilter() method. It is invoked every time when it is requested.
  • public void destroy():  This method is called by servlet container to indicate that all the filtering tasks has been executed. It is invoked once in a lifetime of a servlet.

FilterChain Interface

Servlet container provides FilterChain object to “Filters” for invoking the next filter in the chain. If a current filter is the last filter in the chain then resource of that filter is invoked. This interface provides only one method.

Methods provided by FilterChain interface.

  • public void doFilter(ServletRequest req,ServletResponse res): This method is used to invoke next filter in the chain.

FilterConfig Interface

Servlet container uses the object of FilterConfig interface to provide configuration information to Filter.

Methods provided by FilterChain interface.

  • String getFilterName(): This method returns the value of specific filter name.
  • String getInitParameter(String name): This method returns the value of initialized parameter.
  • Enumeration getInitParameterNames(): This method returns name of initialized parameters in the form of enumeration of string.
  • ServletContext getServletContext(): This method returns the object of ServletContext which is used to communicate servlet container.

Example of Filter

In this example we are creating a registration form using index.html file. Some restriction is applied at the age attribute of this form through DemoFilter.java. Only the users of age 18 or above are eligible to fill this form.

So, if the user age is less than 18 then include() method of RequestDispatcher invokes and generates an error and if it is not then FilterChain object calls the next filter in the chain i.e FilterResult and if the calling filter is the last filter then its resource is invoked.

index.html

<form action="serv">
<h1>Registration form</h1>
<table>
<tr><td><h3>Name:</td><td><input type="text" name="username"> </td></h3></tr> <br>
<tr><td><h3>Email id:</td><td><input type="email" name="user"> </td></h3></tr> <br>
<tr><td><h3>Age:</td><td><input type="text" name="age"></td></h3></tr>
<br>
<tr><td><h3><input type="submit" value="submit"></h3></td></tr>
</table>
</form>

DemoFilter.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName="DemoFilter",urlPatterns= {"/serv"})
public class DemoFilter implements Filter
{
 public void init(FilterConfig con)
 {
 }
 public void doFilter(ServletRequest req,ServletResponse res,FilterChain ch) throws ServletException,IOException
 {
 res.setContentType("text/html");
 PrintWriter pw=res.getWriter();
 String st=req.getParameter("age");
 Integer i=new Integer(st);
 if(i<18)
 {
 pw.println("<h1>Sorry,you are not eligible<h1>");
 RequestDispatcher rd=req.getRequestDispatcher("index.html");
 rd.include(req, res);
 }
 else
 {
 ch.doFilter(req, res);
 }
 }
 public void destroy()
 {
 }
}
FilterResult.java
import java.io.IOException; 
import java.io.PrintWriter;
import javax.servlet.ServletException; 
import javax.servlet.http.*; 
import javax.servlet.annotation.WebServlet;
@WebServlet("/serv")
public class FilterResult extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html"); 
        PrintWriter out = res.getWriter();     
        String name=req.getParameter("username");  
        out.print("<h1>Thank you "+name+"</h1>"); 
        out.print("<br><h1>You have successfully registered</h1>");   
    } 
} 
Output:   This page generates when the age is 18 or above.