Home » Enterprise Java » servlet » Java Servlet Filter Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java Servlet Filter Example

Servlets are modules of the Java code that run in a server application to answer the client requests. In this tutorial, we will explain how to implement the Servlet Filter API to handle the client requests.

1. Introduction

Servlet is a Java program which exists and executes in the J2EE servers and is used to receive the HTTP protocol request, to process it and send back the response to the client. Servlets make use of the Java standard extension classes in the packages javax.servlet and javax.servlet.http. Since Servlets are written in the highly portable Java language and follow a standard framework, they provide a means to create the sophisticated server extensions in a server and operating system in an independent way.

 
Typical uses for HTTP Servlets include:

  • Processing and/or storing the data submitted by an HTML form
  • Providing dynamic content i.e. returning the results of a database query to the client
  • Managing state information on top of the stateless HTTP i.e. for an online shopping cart system which manages the shopping carts for many concurrent customers and maps every request to the right customer

As Servlet technology uses the Java language, thus web applications made using Servlet are Secured, Scalable, and Robust.

1.1 Servlet Architecture & Lifecycle

A Servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of this interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. In this tutorial we’ll be discussing only HTTP Servlets which extends the javax.servlet.http.HttpServlet class.

In order to initialize a Servlet, a server application loads the Servlet class and creates an instance by calling the no-args constructor. Then it calls the Servlet’s init(ServletConfig config) method. The Servlet should perform the one-time setup procedures in this method and store the ServletConfig object so that it can be retrieved later by calling the Servlet’s getServletConfig() method. This is handled by the GenericServlet. Servlets which extend the GenericServlet (or its subclass i.e. HttpServlet) should call the super.init(config) at the beginning of the init method to make use of this feature.

Signature of init() method

public void init(ServletConfig config) throws ServletException

The ServletConfig object contains the Servlet parameters and a reference to the Servlet’s ServletContext. The init method is guaranteed to be called only once during the Servlet’s lifecycle. It does not need to be thread-safe because the service() method will not be called until the call to the init() method returns.

When the Servlet is initialized, its service(HttpServletRequest req, HttpServletResponse resp) method is called for every request to the Servlet. The method is called concurrently (i.e. multiple threads may call this method at the same time) as it should be implemented in a thread-safe manner. The service() method will then call the doGet() or doPost() method based on the type of the HTTP request.

Signature of service() method

public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException

When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server is shutting down), the destroy() method is called. There may still be threads that execute the service() method when the destroy() method is called, so destroy() method has to be thread-safe. All resources which were allocated in the init() method should be released in the destroy() method. This method is guaranteed to be called only once during the Servlet’s lifecycle.

Fig. 1: A Typical Servlet Lifecycle

Fig. 1: A Typical Servlet Lifecycle

1.2 Servlet Filter

A Servlet Filter is an object that is invoked at the pre-processing and post-processing of a request. In other words, it is typically used to perform a particular piece of functionality either before or after the primary functionality that a web application is performed. Servlet Filter is mainly used to perform filtering tasks such as Conversion, Logging, Compression, Request Encryption and Decryption, Input Validation etc.

The Servlet Filter is pluggable i.e. its entry is defined in the web.xml file. If we remove the entry of the servlet filter from the web.xml file, the filter logic will be removed automatically and developers don’t need to change the Servlet.

Fig. 2: A Typical Servlet Chain Workflow

Fig. 2: A Typical Servlet Chain Workflow

1.2.1 Servlet Filter API

Filter API is a part of the Servlet API and is found in the javax.servlet package. For creating a filter, the developer must implement the Filter interface. Filter interface gives the following life-cycle methods for a filter:

  • public void init(FilterConfig filterConfigObj): It is invoked by the web container to indicate that a servlet filter is being placed into the service
  • public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chainObj): It is invoked each time the user request to any resource to which the servlet filter is mapped
  • public void destroy(): It is invoked by the web container to indicate that a filter is being taken out of the service

Note: A FilterChain object is used to invoke the next filter or the resource in the chain.
Now, open up the Eclipse Ide and let’s see how to implement the Servlet Filter in a Java web application!

2. Java Servlet Application for Login Page

Here is a step-by-step guide for implementing the Servlet framework in Java.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 3: Application Project Structure

Fig. 3: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 4: Create Maven Project

Fig. 4: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 5: Project Details

Fig. 5: Project Details

Select the ‘Maven Web App’ Archetype from the list of options and click next.

Fig. 6: Archetype Selection

Fig. 6: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 7: Archetype Parameters

Fig. 7: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaSevletFilter</groupId>
	<artifactId>JavaSevletFilter</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
</project>

We can start adding the dependencies that developers want like Servlets, Junit etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Servlet API. The rest dependencies will be automatically resolved by the Maven framework and the updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>JavaSevletFilter</groupId>
	<artifactId>JavaSevletFilter</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>JavaSevletFilter Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 8: Java Package Creation

Fig. 8: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.filter.

Fig. 9: Java Package Name (com.jcg.filter)

Fig. 9: Java Package Name (com.jcg.filter)

Once the package is created in the application, we will need to create the controller class. Right-click on the newly created package: New -> Class.

Fig. 10: Java Class Creation

Fig. 10: Java Class Creation

A new pop window will open and enter the file name as: Login. The Servlet Filter class will be created inside the package: com.jcg.filter.

Fig. 11: Java Class (Login.java)

Fig. 11: Java Class (Login.java)

Repeat the step (i.e. Fig. 10) and enter the filename as Admin. The Servlet Controller class will be created inside the package: com.jcg.filter.

Fig. 12: Java Class (Admin.java)

Fig. 12: Java Class (Admin.java)

3.2.1 Implementation of Servlet Filter Class

In this example, we are using the Servlet Filter to authenticate (i.e. check correct password). Here index.jsp will ask the username and password. The Servlet Filter class (i.e. Login) will validate the password entered by the user and if the password is correct then the user will be forwarded to the first servlet, else the user will be redirected to the index.jsp.

Fig. 13: Java Servlet Filter Workflow on the Server side

Fig. 13: Java Servlet Filter Workflow on the Server side

Let’s see the simple code snippet that follows this implementation.

Login.java

package com.jcg.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Login implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chainObj) throws IOException, ServletException {

		RequestDispatcher rdObj = null;
		PrintWriter out = resp.getWriter();
		out.write("<html><body><div id='servletResponse' style='text-align: center;'>");

		String password = req.getParameter("password");
		System.out.println("Password Is?= " + password);

		if(password != null && password.equals("admin")) {
			/***** Send Request To Next Resource *****/
			chainObj.doFilter(req, resp);
		} else {
			out.print("<p id='errMsg' style='color: red; font-size: larger;'>Username Or Password Is Invalid. Please Try Again ....!</p>");  
			rdObj = req.getRequestDispatcher("/index.jsp");  
			rdObj.include(req, resp);  
		}

		out.write("</div></body></html>");
		out.close();
	}

	public void destroy() {	}
}

3.2.2 Implementation of Servlet Controller Class

Let’s see the simple code snippet that follows the Servlet Controller implementation in order to show the success response to the user.

Admin.java

package com.jcg.filter;

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 Admin extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		handleRequest(req, resp);
	}

	private void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {		
		resp.setContentType("text/html");

		/***** Building & Printing The HTML Response Code *****/
		PrintWriter out = resp.getWriter();
		out.write("<html><body><div id='servletResponse' style='text-align: center;'>");
		out.write("<h2>Java Sevlet Filter Example</h2>");
		out.write("<p style='color: green; font-size: large;'>Welcome, Administrator!</p>");
		out.write("</div></body></html>");
		out.close();		
	}
}

3.3 Creating JSP Views

Servlet supports many types of views for different presentation technologies. These include – JSP, HTML, XML etc. So let us write a simple view in JavaSevletFilter/src/main/webapp/. Add the following code to it:

index.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
	    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	    <title>Java Sevlet Filter</title>
	    <style type="text/css">
	    	.paddingBtm {
	    		padding-bottom: 12px;
	    	}
	    </style>
	</head>
	<body>
	    <center>
	    	<h2>Java Sevlet Filter Example</h2>
	        <form id="loginForm" action="servlet1">
	            <div id="uDiv" class="paddingBtm">
	            	Username: <input type="text" name="username" />
	            </div>
	            <div id="pDiv" class="paddingBtm">
	            	Password: <input type="password" name="password" />
	            </div>
	            <div id="sDiv">
	            	<input id="btn" type="submit" value="Login" />
	            </div>
	        </form>
	    </center>
	</body>
</html>

3.4 Web Deployment Descriptor

The web.xml is used to define the servlet filter and the filter-mappings. Filters are defined and then mapped to a URL or a Servlet. Add the following code to it:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
   <display-name>Servlet Application Login Example</display-name>
   <servlet>
      <servlet-name>Admin</servlet-name>
      <servlet-class>com.jcg.filter.Admin</servlet-class>
   </servlet>
   <servlet-mapping>
      <servlet-name>Admin</servlet-name>
      <url-pattern>/servlet1</url-pattern>
   </servlet-mapping>
   <filter>
      <filter-name>Login</filter-name>
      <filter-class>com.jcg.filter.Login</filter-class>
   </filter>
   <filter-mapping>
      <filter-name>Login</filter-name>
      <url-pattern>/servlet1</url-pattern>
   </filter-mapping>
</web-app>

4. Run the Application

As we are ready for all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 14: How to Deploy Application on Tomcat

Fig. 14: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it in the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/JavaSevletFilter/

Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 15: Default Login Page

Fig. 15: Default Login Page

Try to enter wrong credentials and the business logic will display the invalid credentials message.

Fig. 16: Invalid Credentials Error Message

Fig. 16: Invalid Credentials Error Message

Now enter the correct credentials as per the configuration (i.e. User: jcg and Password: admin) and the business logic will redirect you to the application’s welcome page.

Fig. 17: Application’s Welcome Page

Fig. 17: Application’s Welcome Page

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to implement the Servlet Filters. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers were looking for.

7. Download the Eclipse Project

This was an example of Servlet Filter Application Login.

Download
You can download the full source code of this example here: JavaSevletFilter
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of