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, sqeezing 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.

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



Below given example discribes the filter implemetation 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>
...
...