J2EE User Authentication using servlet filters



Filters can be used to transform the response from a servlet or a JSP page and can perform many functions as follows

  • User Authentication- Blocking requests based on user identity.
  • Logging and auditing-Tracking users and the actions performed.
  • Image conversion- Scaling, squeezing etc
  • Data compression-For making the download easier.
  • Localization-Targeting the request and response to a particular locale.

A filter is a Java class which implements the javax.servlet.Filter interface . The javax.servlet.Filter interface defines three methods as given below.

SI. NoMethodDescription
1
public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) This method is called each time when a request/response pair is passed.
2
public void init(FilterConfig filterConfig) init() method is used to initialize the filter and this is invoked only once.
3
public void destroy() This method is called to indicate that a filter is being taken out of service

Below given example describes the filter implementation for user authentication

UserAuthFilter.java

package com.servlet.filter.UserAuthFilter ;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
// Implements Filter class
public class UserAuthFilter implements Filter {
 
  private ArrayList urlList;
 
  public void destroy() {
  }
 
  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
 
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String url = request.getServletPath();
    boolean allowedRequest = false;
    String strURL = "";
 
    // To check if the url can be excluded or not
    for (int i = 0; i < urlList.size(); i++) {
      strURL = urlList.get(i).toString();
      if (url.startsWith(strURL)) {
        allowedRequest = true;
      }
    }
 
    if (!allowedRequest) {
      HttpSession session = request.getSession(false);
      if (session == null
          || session.getAttribute("session_uname") == null) {
        // Forward the control to login.jsp if authentication fails
        request.getRequestDispatcher("/login.jsp").forward(request,
            response);
      }
    }
    chain.doFilter(req, res);
  }
 
  public void init(FilterConfig config) throws ServletException {
    // Read the URLs to be avoided for authentication check (From web.xml)
    String urls = config.getInitParameter("avoid-urls");
    StringTokenizer token = new StringTokenizer(urls, ",");
    StrUrlList = new ArrayList();
    while (token.hasMoreTokens()) {
      StrUrlList.add(token.nextToken());
    }
  }
} 

web.xml

<filter>
    <filter-name>UserAuthFilter</filter-name>
    <filter-class>com.servlet.filter.UserAuthFilter </filter-class>
    <init-param>
      <param-name>avoid-urls</param-name>
      <param-value>/login.jsp,/static.jsp</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>UserAuthFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
 

Related Articles

Overriding JAXB binding at client side
Easy Way To Remember SQL Joins - A visual explanation
Setting Expires header in .htaccess to improve your page load time
Login Using Facebook Account - FB Connect
Step By Step Tutorial On LDAP Using Java JNDI
Zoning and LUN Masking

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know