javax.servlet.Filter Interface :-


Filters are used to perform some pre-processing before the request goes to requested servlet or jsp, or some post-processing before response goes back to client.



Note -
One Filter may be registered with multiple servlets or jsp, and one servlet or jsp may be registered with multiple filetrs.
Filters can be used for the following tasks -
1- Data Compression.
2- Data Encryption.
3- Logging and Auditing.
4- Authentication.
5- Image Conversion.
etc.

Filter Methods -

Filter interface has the following methods -
Method name with return type Description
1- public void init(FilterConfig filterConfig)throws ServletException - This method is used to initializing filter and must be complete before filter start filtering task. It is called only once in filter life cycle.
2- public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException This method is called each time when request or response came in to Filter. Here we can perform any pre-processing or post-processing and finally using FilterChain we can forward request or response to the next entity in the chain.
3- public void destroy() It is called just before Filter being destroyed. It allows us to do some work that we want to do before Filter destroyed (for example closing a stream).

Filter LifeCycle -

Like Servlet Filetrs have the following lifecycle -


Registering Filter with servlet or jsp -

To register filter with servlet and jsp, we have to define it in deployment descriptor (web.xml) as follows -
Filter Declaration -
<filter>
  <filter-name>Filter_Name</filter-name>
  <filter-class>Filter_Class</filter-class>
</filter>        
Filter can also have optional initialization parameters -
<filter>
  <filter-name>Filter_1</filter-name>
  <filter-class>filters.Filter_1</filter-class>
 <init-param>
  <param-name>Parameter_Name</param-name>
  <param-value>Parameter_Value</param-value>
 </init-param>
</filter>
Filter Mapping -
<filter-mapping>
  <filter-name>Filter_Name</filter-name>
  <url-pattern>Url_Pattern</url-pattern>  Or <servlet-name>Servlet_Name</servlet-name>
</filter-mapping>            
<url-pattern> - is used to register multiple resources (servlets's and jsp's) in web app to filter according to their url pattern.
<servlet-name> - is used to register a single servlet to filter.

Example 1 -

This basic example will show you, how to create filter and how to register different servlets with filter.

index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>FilterDemo_1</title>
    </head>
    <body>
        <a href="First">First Servlet</a><br>
        <a href="gtn/serv/Second">Second Servlet</a><br>
        <a href="gtn/serv/Third">Third Servlet</a><br>
        <a href="gtn/pkg/Fourth">Fourth Servlet</a><br> 
    </body>
</html>        

2- Create a package named servs and within servs create the following servlets -
First Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class First extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to First Servlet</h1>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Second Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Second extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to Second Servlet</h1>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}

Third Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Third extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to Third Servlet</h1>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}    

Fourth Servlet -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Fourth extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try
        {
            PrintWriter out = response.getWriter();
            out.println("<h1>Welcome to Fourth Servlet</h1>");
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
}

3- Add Servlet information in web.xml.
<web-app>
    <servlet>
        <servlet-name>First</servlet-name>
        <servlet-class>servs.First</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Second</servlet-name>
        <servlet-class>servs.Second</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Third</servlet-name>
        <servlet-class>servs.Third</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Fourth</servlet-name>
        <servlet-class>servs.Fourth</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>First</servlet-name>
        <url-pattern>/First</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Second</servlet-name>
        <url-pattern>/gtn/serv/Second</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Third</servlet-name>
        <url-pattern>/gtn/serv/Third</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Fourth</servlet-name>
        <url-pattern>/gtn/pkg/Fourth</url-pattern>
    </servlet-mapping>
</web-app>        

4- Create Filter - Create a package named filters and with that create a class named Filter_1.
    
package filters;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Filter_1 implements Filter 
{   
    private FilterConfig fconfig;
    public void init(FilterConfig filterConfig)
    {
        fconfig = filterConfig;
    }
    
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)throws IOException, ServletException 
    {
       
        PrintWriter out = response.getWriter();

        // Pre-Processing
        out.println("Filter_1 Starts <br>");

        // Forward the request to requested resource(servlet, jsp, html etc.).
        chain.doFilter(request, response);   

        //Post-Processing 
        out.println("Filter_1 Stops <br>");
    }

    public void destroy() 
    {        
    }   
}    

Register filter with servlets - Add the following code in web.xml -
<web-app>
.........
.........
.........

<filter>
  <filter-name>Filter_1</filter-name>
  <filter-class>filters.Filter_1</filter-class>
</filter>
<filter-mapping>
  <filter-name>Filter_1</filter-name>
  <url-pattern>/*</url-pattern>   <!-- Filter will run with all the resources in web app. -->
</filter-mapping>
</web-app>
We have defined url-pattern to "/*", it means that this filter will run with all the resources (servlet, jsp, html etc) in your web app.
5- Now run the project and it will show you the following output -


Note that filter is running with index.html.

Now click on any link and you will see that filter is running with all the servlets.



Now lets make some changes in filter mapping to run some specific servlets -
<web-app>
.........
.........
.........

<filter>
  <filter-name>Filter_1</filter-name>
  <filter-class>filters.Filter_1</filter-class>
</filter>
<filter-mapping>
  <filter-name>Filter_1</filter-name>
  <url-pattern>/gtn/serv/*</url-pattern>   <!-- Filter will run with all the resources whose url starts with "/gtn/serv/". -->
</filter-mapping>
</web-app>        
Now filter will run with all the resources in the app, whose url starts with "gtn/serv/" and it may contain any thing after that. So now Filter_1 will run with Second and Third servlets only.

Run the project to see the results.

Using <servlet-name> to register filter with servlets -

We can also use <servlet--name> in place of <url-pattern> to register servlets with filter. In contrast with <url-pattern>, <servlet--name> can only register one servlet with filter at a time.
To register First and Second servlet with filter, we have to register them one by one as follows -
<web-app>
.........
.........
.........

<filter>
  <filter-name>Filter_1</filter-name>
  <filter-class>filters.Filter_1</filter-class>
</filter>

<filter-mapping>
  <filter-name>Filter_1</filter-name>
  <servlet-name>First</servlet-name>  <!-- Registering First servlet with filter.-->
</filter-mapping>
<filter-mapping>
  <filter-name>Filter_1</filter-name>
  <servlet-name>Second</servlet-name> <!-- Registering Second servlet with filter.-->
</filter-mapping>

</web-app>        
Now filter will run with First and Second servlets only.

Example 2 -

In this example we will use two filters, one for defining the header of our website, and other for Authenticating user by checking user name and password.

1 - index.html or index.jsp - This will be your default page.
<!DOCTYPE html>
<html>
    <head>
        <title>FilterDemo_2</title>
    </head>
    <body>
        <form method="post" action="WelcomeServ">
            <table border="1px">
                <tr>
                    <td>UserName </td>
                    <td><input type="text" name="t1"></td>
                </tr>
                <tr>
                    <td>Password </td>
                    <td><input type="password" name="t2"></td>
                </tr>
                <tr>
                    <td><input type="submit" value="Login"></td>
                    <td><input type="reset" value="Reset"></td>
                </tr>
            </table>
        </form>

    </body>
</html>         

2- Create a package named filters and within that create the following filters -
Filter_1 Filter -
This will be used as a Header of our website and will run with all the resources(servlet, jsp, html) in our web-app.

package filters;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Filter_1 implements Filter
{
    FilterConfig fg;
    
    public void init(FilterConfig config)
    {
        fg = config;
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        
        PrintWriter out = response.getWriter();
        out.println("<table border='1px' width='100%' style='text-align:center'");
        out.println("<tr>");
        out.println("<td colspan='4'>");
        out.println("<h1 style='padding:10px'>MyWebsite Title</h1>");
        out.println("</td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td>");
        out.println("<a href='#'>Link1</a>");        
        out.println("</td>");
        out.println("<td>");
        out.println("<a href='#'>Link2</a>");        
        out.println("</td>");
        out.println("<td>");
        out.println("<a href='#'>Link3</a>");        
        out.println("</td>");
        out.println("<td>");
        out.println("<a href='#'>Link4</a>");        
        out.println("</tr>");
        out.println("</table>");  
        chain.doFilter(request, response);
    }
    
    public void destroy()
    {  
    }    
}   

Filter_2 Filter -
This will be our Authentication filter. It will check username and password entered by user. It will run with WelcomeServ(defined next) only.

package filters;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Filter_2 implements Filter
{
    FilterConfig fg;
    
    public void init(FilterConfig config)
    {
        fg = config;
    }
    
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest http_request = (HttpServletRequest)request;
        HttpServletResponse http_response = (HttpServletResponse)response;
        
        PrintWriter out = response.getWriter();
      
        // create a session
        HttpSession session = http_request.getSession();
        
        String nm = request.getParameter("t1");
        String ps = request.getParameter("t2");
        if(nm.equals("Admin") && ps.equals("123"))
        {
            // if user enter correct username or password, then create a Status attribute and set it to true. 
            session.setAttribute("Status", true);
            chain.doFilter(request, response);
        }
        else
        {
            //if user enter incorrect username or password, then set Status to true.
            session.setAttribute("Status", false);
            chain.doFilter(request, response);
        } 
    }
    
    public void destroy()
    {
    }    
}

3- Create a package named serv and within that create a servlet named WelcomeServ.

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServ extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
      try
      {
          PrintWriter out = response.getWriter();
          HttpSession session = request.getSession();
          
          if((Boolean)session.getAttribute("Status"))
          {
              out.println("<h1>Welcome Home</h1>");
          }
          else
          {
              out.println("Wrong Username or password");
              RequestDispatcher rdp = request.getRequestDispatcher("index.html");
              rdp.include(request, response);
          }
          
      }
      catch(Exception ex)
      {
          System.out.println(ex);
      }
    }
}        

4- web.xml -
<web-app>
    <servlet>
        <servlet-name>WelcomeServ</servlet-name>
        <servlet-class>servs.WelcomeServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>WelcomeServ</servlet-name>
        <url-pattern>/WelcomeServ</url-pattern>
    </servlet-mapping>
  
  <filter>
        <filter-name>Filter_1</filter-name>
        <filter-class>filters.Filter_1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Filter_1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  <filter>
        <filter-name>Filter_2</filter-name>
        <filter-class>filters.Filter_2</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Filter_2</filter-name>
        <url-pattern>/WelcomeServ</url-pattern>
    </filter-mapping>
      
</web-app>   

6- Now run your project and you will see the following output -



If you enter correct username and password (Admin/123 in our example), you will see the following output -



If you enter incorrect username or password, you will see the following output -