Servlet filters in java with login Filter example. How to configure web.xml for servlet filters?

               This tutorial covers that what is servet filter and its uses. Also covers that how to configure web.xml for handling filters.  Servlet filters are powerful tools that are introduced in servlet specification version 2.3 which simplifies various tasks to web application developers by providing the ability to convert recurring tasks in reusable units which can be reused in many different contexts.

Filters are used to

             a) manipulate or use the information contained in the requests before they are  access ed by a servlet by intercepting the requests

           b) manipulate responses before they send back to the client  by intercepting responses.

More than one filters are allowed in a single web application that can act on the request & responses. Java provides Filter interface to implement servlet filters. Filters are configured in the deployment descriptor (web.xml) for a web application.

Filters have a wide range of uses. The following areas are suggested by the servlet 2.3

1) Authentication Filters : Additional authentication or additional processing may be required before and after authentication. For example, blocking requests based on user identity by creating LoginFilter

2. Serverside validations : Each parameters passed in the request can be validated using Regex or other mechanism  before they are sent to  a servlet.

3. Logging and Auditing Filters : Information like username, ipaddress, etc from the requests are captured in a log files by creating LoggingFilter which may be used to track users of a web application

4) Image conversion Filters : Image Conversion Filter can be created for scaling images, and so on. (For eg. scaling of map)

5) Data compression Filters : Compression filter may be created to optimize the size of the content (may use java.util.zip.GZIPOutputStream class) that you send from your web server to a user .

6) Encryption Filters : Contents of the requests can be be encoded by any encription technique like utf-8 by creating UTF8Filter and more..

Writing a filter :

To write a filter, we create a class implementing the Filter interface, which has three methods

init() : init method is called exactly once when the filter is instantiated. It can be used to do initalization and configurations. The following lines are used in init() method in the below example program.


public void init(FilterConfig filterConfig) throws ServletException {
 this.filterConfig = filterConfig;
 blockedList = new java.util.ArrayList();
 readBlockedList(); // to invoke list of unauthorized users.
}

Note : Filter cannot proceed further if the init method throws a ServletException.

doFilter() : doFilter() method is called before the servlet to which this filter is mapped.


 <filter-name>LoginFilter</filter-name> 

<url-pattern>/processLogin</url-pattern>

In this example,  LoginFilter is mapped with processLogin servlet. LoginFilter is called before processLogin servlet is called.

The following lines (partial) are used in the doFilter() method in the example program.


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException {
 HttpServletRequest req = (HttpServletRequest)request;
 HttpServletResponse res = (HttpServletResponse)response;
 String username = req.getParameter("loginId");
 .......
}

The request from the client browser is sent to the first servlet in the chain. The response from the last servlet in the chain is returned to the browser. The output from each servlet is the input to the next servlet.

doFilter() can be implemented to do any of the following typical tasks

1. Examine the request to allow further or block

2. Wraping the request / response object to manipulate content or headers for input / output filtering respectively.

3. Either call chain.doFilter() to invoke the next entity in the chain using the FilterChain object or don’t call if you need to block the request processing.

destroy() : destroy() are called when the filter is destroyed to clean up any resources that are being held (for eg. memory, file handles, threads). The following lines are used in the destroy() methd in our example.


public void destroy() {
this.filterConfig = null;
blockedList = null;
}

Authentication Filters for blocking requests based on user identity. For this we can create a LoginFilter class which implements filter interface. This is an additional authentication. In this, we have a file blockedUsersList.txt which contains the blocked list of users. The filter’s init() method gets filename using filterConfig.getInitParameter which is configured as a parameter in the web.xml. doFilter() method gets the userName from the request and checks the blockedList contains in the userName.  If blockedList contains the userName, then the request is blocked without calling the chain.doFilter method and is redirected to some other error page.

Note : If a servlet maps to many servlet filters, servlet filters are called in the order that is listed in the web.xml deployment descriptor of the application.


package Filters;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LoginFilter implements Filter {
protected FilterConfig filterConfig;
java.util.List blockedList;

//init method
public void init(FilterConfig filterConfig) throws ServletException {
   this.filterConfig = filterConfig;
   blockedList = new java.util.ArrayList();
   readBlockedList();
}

//do filter method
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException {
   HttpServletRequest req = (HttpServletRequest)request;
   HttpServletResponse res = (HttpServletResponse)response;
   String username = req.getParameter("loginId");
   if ( blockedList.contains(username) ) {
     try {
          req.getRequestDispatcher( "/unauthorisederror.jsp").forward( request, response); // if blocked list contains the  username , then error page called.
         } catch (Exception ex) {
           ex.printStackTrace();
      }
     return;
    }
     chain.doFilter(request, response);
}

//destroy method to clean up.
public void destroy() {
   this.filterConfig = null;
   blockedList = null;
}


//method to read all blocked user list from the file d:\javaonline\users\blockedUsersList.txt
private void readBlockedList() {
if ( filterConfig != null ) {
   BufferedReader in;
   String blockedUserName;
   try {
      String filename = filterConfig.getInitParameter("BlockedUsers");
      in = new BufferedReader( new FileReader(filename));
       } catch ( FileNotFoundException fnfe) {
    return;
      }
   try {
     while ( (blockedUserName = in.readLine()) != null )
         blockedList.add(blockedUserName);
        } catch (IOException ioe) {
      }
     }
    }
   }

Configuring servlet filters in web.xml:

Filter class : to mention filter class (Filters.LoginFilter) where Filters is packegae

We need to pass the file name which contains blocked users. that can be configured in web.xml by the param-name & param-value

here LoginFilter is mapped with servlet /processLogin

web.xml configuration for Filters

 <filter>
 <filter-name>LoginFilter</filter-name>
 <filter-class>Filters.LoginFilter</filter-class>
 <init-param>
 <param-name>BlockedUsers</param-name>
 <param-value>d:\javaonline\users\blockedUsersList.txt</param-value>
 </init-param>
 </filter>

 <filter-mapping>
 <filter-name>LoginFilter</filter-name>
 <url-pattern>/processLogin</url-pattern>
 </filter-mapping>

Note : For running the above filters, create login.jsp and processLogin servlet. login.jsp has the fields loginId & password. LoginFilter is called before the servlet processLogin is called. The processLogin servlet performs the authentication and servlet filters(LoginFilter) perform additional authentication.

d:\javaonline\users\blockedUsersList.txt is the path where blockedUsersList.txt file located.

Reference : http://www.oracle.com/technetwork/java/filters-137243.html

You may also like

Leave a Reply