Friday 22 August 2014

Filtering

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Before dig into further will see an application which uses filters.


As you see the above figure, If you are using filters, then any request sent by client must pass through the filters configured by you in web.xml file, before reach the final endpoint or resource. Response also same like in reverse way.

When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

The class using the filters should extend javax.servlet.Filter. Every request in a web application, the servlet container decides the filters to apply and adds them to the filter chain, in the order they appear in web.xml file.

Configuring the Servlet Filter in web.xml
<filter>
        <filter-name>Filter1</filter-name>
        <filter-class>Filter1</filter-class>
</filter>
<filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/Home</url-pattern>
</filter-mapping>

With this configuration all requests with URL '/Home' will be intercepted by the servlet filter.

Lets try to implement a simple example, where client has to enter his name,
  1. If the client name is 'blockme' then filter1 blocks this client and send response like 'you are not authorized to access this application'
  2. If the client name is not 'blockme' then filter1 forward this request to filter2. Filter2 checks for length of the username. If the length is less than 6, then send response like 'Username length is less than 6', else forward the request to welcome servlet.
Main.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   
     <title>Filter Example</title>
    </head>
    <body>
        <form method="post" action="/servlet/Home">
            <input type="text" name="userName">
            <input type="submit" value ="Get Data">
        </form>
    </body>
</html>

Filter1.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class Filter1 implements Filter {
   @Override
   public void init(FilterConfig filterConfig) throws ServletException{
       
   }
   
   @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
        try(PrintWriter out = res.getWriter()){
          String userName = req.getParameter("userName");
          if(userName.equals("blockme")){
              out.println("you are not authorized to access this application");
          }
          else{
              out.println("Filter1 forwarding request");
              chain.doFilter(req, res);
              System.out.println("Filter1 finished");
          }
      }
    }
    
   @Override
    public void destroy(){
        
    }
}

Filter2.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;


public class Filter2 implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException{
       
   }
   
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
        try(PrintWriter out = res.getWriter()){
          String userName = req.getParameter("userName");
          if(userName.length() < 6){
              out.println("Username length is less than 6");
          }
          else{
              out.println("Filter2 forwarding request");
              chain.doFilter(req, res);
              System.out.println("Filter2 finished");
          }
      }
    }
    
    @Override
    public void destroy(){
        
    }
    
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <filter>
        <filter-name>Filter1</filter-name>
        <filter-class>Filter1</filter-class>
    </filter>
    <filter>
        <filter-name>Filter2</filter-name>
        <filter-class>Filter2</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/Home</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>Filter2</filter-name>
        <url-pattern>/Home</url-pattern>
    </filter-mapping>
    
    <servlet>
        <servlet-name>Welcome</servlet-name>
        <servlet-class>Welcome</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Welcome</servlet-name>
        <url-pattern>/Home</url-pattern>
    </servlet-mapping>
</web-app>

Welcome.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Welcome extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
      try(PrintWriter out = res.getWriter()){
          String userName = req.getParameter("userName");
          out.println("Welcome " + userName);
      }
  }
}

Output
1. for the input 'blockme'



2. For the input less than 6 characters



3. For the input 'Krishna'










Prevoius                                                 Next                                                 Home

No comments:

Post a Comment