practical example of a filter

In this post, you will learn:

  • How to define a filter?
  • How to associate filters to requests?
  • How to redirect non authenticated users to the home page using a filter?

A scenario for the practical use of a filter:

To demonstrate the practical use of a filter in a web application, I am creating a filter which checks the URI of each incoming request. If the request is for the home page or the servlet which authenticates, simply requested component is invoked by the filter. Otherwise user session is checked, if session doesn’t exists it means the user has not authenticated itself and trying to access a resource which is for the authenticated users only hence it is redirected to the home page for login. you must have seen such functionality in popular web sites such as gmail, facebook etc.

The example application has following components: index.html, entryServlet, exitServlet and FlowController filter. index.html and entryServlet are the public resources of the application which can be requested by the unauthenticated users. exitServlet is the protected resource which can only be used by authenticated users.

Source code of the practical example of a filter:

First, the index.html :

<form method="post" action="entryServlet">
Name <input type="text" name="name"> <br/>
<input type="submit" value="submit">
</form>

Second, the FlowController filter :

package com.techmentro.learningpad;

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


public class FlowController implements Filter {

	//Data Member to store the reference of the FilterConfig object 
	private FilterConfig config;
	
	@Override
	public void init(FilterConfig config) throws ServletException {
		// Reference of the FilterConfig object provided by the server is saved for future use.
		this.config=config;
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//ServletRequest is type casted to HttpServletRequest so that session can be obtained.
		HttpServletRequest req=(HttpServletRequest)request;
		
		
		//Request URI is obtained
		String uri=req.getRequestURI();
		//URI of the login servlet which is provided to the filter as initialization parameter is obtained.
		String entryServlet=config.getInitParameter("ServletToLogin");
		//Request URI is checked whether request is for a public resource or protected resource
		if(uri.endsWith("html") || uri.endsWith(entryServlet))
		{
			//request is for public resource, get the requested resource invoked.
			chain.doFilter(request, response);
		}
		else
		{
			//request is for protected resource, check whether user has authenticated itself or not.
			//Reference of the existing session is obtained. If session doesn't exists, new session isn't created.
			HttpSession session=req.getSession(false);
			if(session!=null)
			{
				//User has authenticated itself, get the requested resource invoked.
				chain.doFilter(request, response);
			}
			else
			{
				//User hasn't authenticated itself, redirects it to the home page.
				RequestDispatcher rd=request.getRequestDispatcher("index.html");
				rd.forward(request, response);
			}
		}
	}

	
	@Override
	public void destroy() {	}

}

Third, the EntryServlet:

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class EntryServlet extends HttpServlet 
{
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		String user=request.getParameter("name");
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		out.println("Welcome, "+user);
		HttpSession session=request.getSession();
		session.setAttribute("user", user);
out.println("<br> exit");
		out.close();
	}
}

Fourth, the ExitServlet:

package com.techmentro.learningpad;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class ExitServlet extends HttpServlet 
{
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session=request.getSession();
		String user=(String)session.getAttribute("user");
		session.invalidate();
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
	out.println(user+", you have successfully exited.");
out.println("<br> try again");
	out.close();
	}
}

Fifth, the web.xml. It has <filter> and <filter-mapping> elements to register the filter to the server and to associate it to the requests respectivley.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 
 
<!--Filter is registered and associated to all static and dynamic requests.  -->
 <filter>
 <filter-name>f1</filter-name>
 <filter-class>com.techmentro.learningpad.FlowController</filter-class>
 <init-param>
 <param-name>ServletToLogin</param-name>
 <param-value>entryServlet</param-value>
 </init-param>
 </filter>
 
 <filter-mapping>
 <filter-name>f1</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
 
 <servlet>
 <servlet-name>s1</servlet-name>
 <servlet-class>com.techmentro.learningpad.EntryServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>s1</servlet-name>
 <url-pattern>/entryServlet</url-pattern>
 </servlet-mapping>
 <servlet>
 <servlet-name>s2</servlet-name>
 <servlet-class>com.techmentro.learningpad.ExitServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>s2</servlet-name>
 <url-pattern>/exitServlet</url-pattern>
 </servlet-mapping>
 <servlet>
 
</web-app>

To test this application use following steps:

1. After deploying the application on a web server, send a direct request for the exitServlet using following url: http://localhost:8080/filterApp/exitServlet. If port no of your server is different, then use that in place of 8080. You will be redirected to the index.html because no session exists for you on the server.

2. Submit the request to the entryServlet using the form of index.html. You will receive its normal response, which has welcome message as well as hyper link for exit servlet. A session will be created on the server for you.

3. Send the request to the exitServlet using the hyper link. You will receive its normal response because when request is sent session existed on the server. This session is invalidated by the exitServlet.

4. Try refreshing this page i.e. resend request to exitServlet. Now you will be redirected to the index.html again because the session was destroyed in the previous request.


If you like the post, then share it...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *