Filters in JSP

JSP Filters with Examples

In this article, I am going to discuss Filters in JSP with Examples. Please read our previous article where we discussed Form Processing in JSP. At the end of this article, you will understand the following pointers.

  1. What is JSP Filter?
  2. Where Do We Use Filters?
  3. How does JSP Filter work?
  4. The life cycle of the JSP filter?
  5. Advantages of Filter
  6. JSP Filter Interface / What are the interfaces/methods?
  7. JSP Filter Configuration
  8. Using Multiple Filters
  9. JSP Filter Ordering
  10. JSP Filter Examples
  11. How filter can intercept the request
  12. Write a filter example to read all the init parameters and display them on the screen
  13. Filter Chaining
  14. Type of Filtering
What are JSP Filters?

JSP Filters are used to manipulate the server’s response and to intercept the requests from a client with the help of a Java class. It is also used to authenticate the credentials of the user and to perform data encryption techniques on the data. It is also used for modification, alteration, encryption, decryption, and compression of data. A filter is an administrator task but not a presentation layer task because it is something we used to do behind the servlets. The filters can be mapped to either JSP names or URL patterns in the web.xml file so the filters execute in the order that they are pronounced. It is basically used for filtering the functionality of Java web applications.

Syntax:
<filter>
<filter-name></filter-name>
<filter-class></filter-class>
</filter>
<filter-mapping>
<filter-name></filter-name>
<url-pattern></url-pattern>
</filter-mapping>

Where do we use Filters?

In a web application if you want to send large data to the server then it will take more time. And when we are requesting the page, we cannot stop it anywhere in between, the page has to go-to target. Here, if we are using a filter then we are allowed to do something even after submitting the form because it is used between requests until the request reaches the target. We can write sensitive data into the filter instead of writing it in the core business servlet. The filter is also used to compress the data between the data posted and the data received by the server. Also, the developer should not write login codes on the servlet page because if the data got leaked a hacker can easily use SQL injection to leak the entire code.

How does JSP Filter work?

The java filters are used to intercept the client requests and manipulate the response for each client requests from the server. It is also used to authenticate the users as well as data to be more secured like encrypting the data and use it to store the user details. The filter interface can be implemented by using javax.servlet.class. The java web applications can be filtered with the help of different filtering functionalities. We are defining filters in the web.xml file and mapping it into the servlet or JSP so it automatically creates the instance of each filter deployed in the web.xml deployment descriptor file when we run the JSP codes. We can also use multiple filters in JSP. We can use Authentication filters to validate the user details. We can use compression filters to compress the user’s data. We can use encryption filters to encrypt the user data. By using filters, we can use the images for highlighting the web pages more attractively. We can write the sensitive codes in filters by avoiding it writing in the servlets as it not secured. It is also used for storing the IP address of every user logins and in the string replacements. We can easily concatenate the strings and data using filters.

How does JSP Filters work?

Life Cycle of JSP Filter

The JSP Life Cycle is very similar to Servlet Life Cycle. There are four major stages as described below:

  1. Compilation Stage: When a page is requested first, the engine checks if it is compiled or not. If it hasn’t been compiled earlier then the engine will compile the page at first by following three main processes, i.e. parsing the page, turning it into a servlet, and then compiling the page.
  2. Initialization Stage: After compilation of the JSP page when the container loads the JSP page, the jspInit() method has been issued before processing the request.
  3. Execution Stage: In this stage, the interaction of JSPs has happened until its termination. The engine issues _jspService() method when the JSP has loaded in the browser and initialized. This method is issued only once per user and helps to generate server responses.
  4. Clean-up Stage: This is the last stage of the JSP life cycle. In this stage, the JSP is destroyed after its use by using the jspDestroy() method. It is used for cleaning up before destroying the page.
Types of JSP Filters
  1. Logging Filters: It is used to log in the times for incoming requests and outgoing responses in the logs. When you want to log any information on the server, you can use logging filters.
  2. Data Compression Filters: When you want to compress the data to a certain extent, you can use data compression filters. Here data is compressed to the required percentage by these filters and then communicated accordingly.
  3. Tokenizing Filters: By using tokenizing filters, all the user data are stored and retrieved.
  4. Encryption Filters: This filter is used to encrypt and save the user data that is flowing through the filters.
  5. Authentication Filters: This filter is used for the authentication of all the users based on the preset criteria.
Advantages of JSP Filters
  1. JSP filter is reusable.
  2. It allows us to separate the business logic from the presentation layer.
  3. Instead of writing business logic in the servlet or JSP, we can write it in the filter.
  4. We can easily apply filters on any presentation layer code.
  5. JSP Filter allows you to apply wholesale changes to an existing resource.
JSP Filters Interfaces/Methods
  1. public void doFilter(ServletRequest, ServletResponse, FilterChain): This method is used when a request/response pair is passed from every client when it is requested from a resource.
  2. public void init(FilterConfig): This method is used to indicate that the filter is placed into service.
  3. public void destroy(): This method is used to indicate the filter has been taken out of service.
JSP Filter Configuration
  1. Download and install JDK and set the PATH and JAVA_HOME.
  2. Download and install Tomcat Web Server and set up the classpath for the servlet class.
  3. Now create the filter implementation Java class which is called for any client request which takes the initialization parameter values from the web.xml file.
FilterJSP.java
package Action;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class FilterJSP implements Filter {
 // This is the initialization method
 public void init(FilterConfig confg) throws ServletException {
  // Get initialization parameters
  String initParam = confg.getInitParameter("init-param");
  // Check initialization parameter values
  System.out.println("Initialization Parameters: " + initParam);
 }

 // This is the execution method
 public void doFilter(ServletRequest req, ServletResponse res, FilterChain fltrchain)
   throws java.io.IOException, ServletException {
  // Get client URI.
  String clientURI = req.getRequestURI();
  // Print client URI and time stamp
  System.out.println("Client URI: " + clientURI + ", Time Stamp: " + new Date().toString());
  // Pass data to the filter chain
  fltrchain.doFilter(req, res);
 }

 // This is the last life cycle method
 public void destroy() {
  // This is the clean-up life cycle method
 }
}

4. Now create a configuration file where all the filters are defined in a particular order and add URL mapping also. Also, we can add multiple filters and add them in a proper sequence.

web.xml
<filter>
   <filter-name>FilterJSP</filter-name>
   <filter-class>FilterJSP</filter-class>
   <init-param>
                  <param-name>init-param</param-name>
                  <param-value>Demo init filter parameters</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>FilterJSP</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

5. At last compile the java class and place it in the webapps/ROOT/WEB-INF/classes folder. We are defining the mapping as (/*), so when you call the JSP pages it will execute the filter class and log the output in the webserver log.

Multiple Filters in JSP

We can use multiple filter-mapping elements in web.xml. The order in which the web container applies the filter to the JSP is determined by the order of filter-mapping elements in the web.xml deployment descriptor file. Following code shows how to use two filters in the web.xml file:

web.xml
<filter>
   <filter-name>FilterJSP</filter-name>
   <filter-class>FilterJSP</filter-class>
   <init-param>
    <param-name>test-param</param-name>
    <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
 
<filter>
   <filter-name>MyFilter</filter-name>
   <filter-class>MyFilter</filter-class>
   <init-param>
    <param-name>test-param</param-name>
    <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
 
<filter-mapping>
   <filter-name>FilterJSP</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
 
<filter-mapping>
   <filter-name>MyFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
Filter Ordering in JSP

The order in which the web container applies the filter to the JSP is determined by the order of filter-mapping elements in the web.xml deployment descriptor file. If you want to reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.

Example:
<filter-mapping>
   <filter-name>MyFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
   <filter-name>FilterJSP</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
Filter Example in JSP

In this example, in the filter.jsp we have written a sample code. FilterJSP.java is the class file where init() is indicating that a filter is placed into service and destroy() method is indicating that the filter s taken out of service. In the web.xml file, the URL pattern has been included in the tag class name which has been mentioned with its package.

filter.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Filter Demo</title>
</head>
<body bgcolor="skyblue">
 <strong> Welcome, This is filter Demo !!! </strong>
</body>
</html>
FilterJSP.java
package Action;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class FilterJSP implements Filter {
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  System.out.println("Filter A initialized...");
 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
   throws IOException, ServletException {
  System.out.println("Filter A executing Before JSP Processing ...");
  filterChain.doFilter(request, response);
  System.out.println("Filter A executing after JSP Processing...");
 }

 @Override
 public void destroy() {
  System.out.println("Filter A Destroyed..");
 }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <display-name>filters</display-name>
 <welcome-file-list>
  <welcome-file>filter.jsp</welcome-file>
 </welcome-file-list>
 <filter>
  <filter-name>FilterJSP</filter-name>
  <filter-class>Action.FilterJSP</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>FilterJSP</filter-name>
  <url-pattern>/filter.jsp</url-pattern>
 </filter-mapping>
</web-app>
Output

Run your code to get the following output:

Filter Example in JSP

How filters can intercept the request in JSP?

Let us see an example to see how a filter can intercept the request. First, create a JSP file where we will read and display the request parameter. Then create a java file where we will write filter code which will be applied on the created JSP file and also take the value of the request parameter and examine if it is empty or not. The filter will respond back with an error message and will not pass it to the JSP file if the value is empty. If the value is not empty, it will be executed and response back with the value.

RequestInterceptor.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Protected JSP</title>
</head>
<body>
 <%
  String name = request.getParameter("name");
 %>
 <strong> Value Entered by User is :: </strong>
 <%=name%>
</body>
</html>
RequestInterceptor.java
package Action;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class RequestInterceptor implements Filter {
 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  System.out.println("Filter  initialized...");
 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
   throws IOException, ServletException {
  String name = request.getParameter("name");
  if (name == null || name.equals("")) {
   PrintWriter writer = response.getWriter();
   String message = "Name cannot be blank.( This is the response from Protected Servlet )";
   writer.println(message);
   return;
  }
  filterChain.doFilter(request, response);
 }

 @Override
 public void destroy() {
  System.out.println("Filter  Destroyed..");
 }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
 <display-name>filters</display-name>
 <welcome-file-list>
  <welcome-file>RequestInterceptor.jsp</welcome-file>
 </welcome-file-list>
 <filter>
  <filter-name>RequestInterceptor</filter-name>
  <filter-class>Action.RequestInterceptor</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>RequestInterceptor</filter-name>
  <url-pattern>/RequestInterceptor.jsp</url-pattern>
 </filter-mapping>
</web-app>

Output

How filters can intercept the request in JSP?

Reading all init parameters and displaying them on screen

In JSP Filter, we can read the init parameters through FilterConfig which is provided in the initialization method, where we can define an instance variable and map it to the one passed in the init() method.

InitParameterFilter.java
package Action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class InitParameterFilter implements Filter {
 private FilterConfig filterConfig = null;

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {
  System.out.println("Filter  initialized...");
  this.filterConfig = filterConfig;
 }

 @Override
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
   throws IOException, ServletException {
  Enumeration<String> initParams = filterConfig.getInitParameterNames();
  StringBuffer buffer = new StringBuffer();
  while (initParams.hasMoreElements()) {
   String initParamName = initParams.nextElement();
   String initParamValue = filterConfig.getInitParameter(initParamName);
   buffer.append(initParamName + "::" + initParamValue+"\n\n");
  }
  PrintWriter writer = response.getWriter();
  writer.println(buffer.toString());
 }

 @Override
 public void destroy() {
  System.out.println("Filter  Destroyed..");
 }
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
    <filter-name>InitParameterFilter</filter-name>
    <filter-class>Action.InitParameterFilter</filter-class>
    <init-param>
        <param-name>parameter1</param-name>
        <param-value>Hello</param-value>
    </init-param>
    <init-param>
        <param-name>parameter2</param-name>
        <param-value>World</param-value>
    </init-param>
    </filter>
<filter-mapping>
    <filter-name>InitParameterFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Output

Filters in JSP with Examples

Filters Chaining in JSP

Filter Chaining is used to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain. We are allowed to use multiple filters as the filter never goes to the end-user and works in the background.

Types of Filtering in JSP

There are two ways of Filtering:

  1. The filter of Request: It modifies the request headers and data by providing a customized version of the request. If you want to note the IP address of the users who visits your website, so we can write a filter for that which will always execute before the servlet. We are not writing the code in servlet because this is an administrative task.
  2. The filter of Response: It modifies the response headers data by providing a customized version of the response. The filter is always a kind of treatment on data in request and response. The server always gives different responses but the user gets different responses treated by the filter whenever we want to treat response data.

In the next article, I am going to discuss JSP Session Tracking. Here, in this article, I try to explain Filters in JSP with Examples. I hope you enjoy this Filters in JSP article.

Leave a Reply

Your email address will not be published.