Servlet Filter Example

A Servlet filter is an object that is used to intercept HTTP requests.Servlet Filter facilitates programmer by pre-processing and post processing means Filter invoked before request is process and after request is processed.

Servlet Filter can be used to do the following.

  • Validation
  • Authentication
  • Encryption
  • Logging and Auditing
  • Image Conversion

Lets assume there are two filters named f1 and f2 which is added to a request.When a request comes for same Servlet container invokes each filter associated with request.See following scenario below for the same.

 

fiilter

javax.servlet.Filter interface provides the API to create filters.

Methods of Filter Interface

  • public void doFilter (ServletRequest, ServletResponse, FilterChain): This main method which invokes by Servlet container if a request is associated with filters.FilterChain interface provides doFilter() method to invoke next chained filter or servlets.
  • public void init(FilterConfig filterConfig): This method is used to initialize the filter object.This method invokes only once during its life cycle.
  • public void destroy():¬† This method is used to destroy or release resources acquired by filter object.

Here I am going to validation form inputs elements by using Filter.

Project Files

  • RegisterServlet.java
  • ValidationFilter.java
  • register.jsp
  • index.jsp
  • web.xml

Required Jars

  • servlet-api.jar
  • jstl-1.2.jar

RegisterServlet.java


package com.startwithjava;
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 RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<h1>Thanks for registrating with us</h1>");
}
}

ValidationFilter.java


package com.startwithjava;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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.RequestDispatcher;
public class ValidationFilter implements Filter {
public ValidationFilter() {

}

public void destroy() {

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest rq = (HttpServletRequest)request;
HttpServletResponse rs = (HttpServletResponse)response;
String name = rq.getParameter("name");
String email = rq.getParameter("email");
String password = rq.getParameter("password");
List<String> list = new ArrayList<String>();
System.out.println("Validation filter called name"+name);
int error =0;
if(name.isEmpty()){
error=1;
list.add("Please enter name");
}
if(email.isEmpty()){
error=1;
list.add("Please enter email");
}
if(password.isEmpty()){
error=1;
list.add("Please enter password");
}
if(error==0)
chain.doFilter(request, response);
else{
RequestDispatcher rd = rq.getRequestDispatcher("/register.jsp");
rq.setAttribute("errors", list);
rd.include(rq, rs);
}

}
public void init(FilterConfig fConfig) throws ServletException {
}

}

index.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>LoginServlet Example</title>
</head>
<body>
<a href="register.jsp">Register</a>
</body>
</html>

register.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=ISO-8859-1">
<title>Filter Validation Example</title>
</head>
<body>
<c:forEach items="${errors}" var="error">
<p style="color:red;"><c:out value="${error}"/></p>
</c:forEach>
<h1>Filter Validation Example</h1>
<form action="register" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password"></td>
</tr>
<tr>
<td><input type="submit" name="Register" value="Register"></td>
</tr>
</table>
</form>
</body>
</html>

web.xml


<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<filter>
<filter-name>f1</filter-name>
<filter-class>com.startwithjava.ValidationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/register</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.startwithjava.RegisterServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>

Leave a Reply