Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
JSP and Servlet Filters are Java classes, used to manipulate the server's responses before sending them back to the client. Filters are used to intercept requests from a client before they access a resource at the back-end.
JSP filter is mainly used to perform filtering tasks such as compression, conversion, encryption, logging and decryption, input validation etc.
There are many features to customize the web pages using JSTL tags, customized tags, and elements in JSP.
What is JSP Filter?
JSP filters, one of the features for iterating the data or sorting the data based on the user requirements, mainly reduce the time complexity of the programs. To manipulate the server’s response and intercept the requests from a client, JSP has its proprietary filters used with the help of a java class. At the same time, the filters are used to authenticate the user's credentials and perform data encryption techniques on the data in question.
JSP Filters are defined in the web.xml file and will be mapped into the URL patterns or JSP. Whenever we compile the jsp codes, it starts the jsp containers and automatically creates the instance of each filter that will be deployed in the deployment descriptor file.
The JSP (JavaServer Pages) filters are nothing but the java classes that can be used to intercept the client requests or manipulate the response for each client requests from the servers.
The filter interface can be implemented by using javax.servlet.class. With the help of different filtering functionalities, java web applications can be filtered. We define filters in the web.xml file and map it into the servlet or JavaServer Pages. So, it automatically creates the instance of each filter deployed in the web.xml deployment descriptor file when we execute the JavaServer Pages codes.
We can use multiple filters in JavaServer Pages. Authentication filters are used 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. We can use the images to highlight the web pages more attractively by using filters.
It is also used for storing the internet protocol (IP) addresses of every user's logins and also for string replacements. We can concatenate the strings and data using filters.
Types of JSP Filters
Logging Filters: We can use logging filters to log any information in the backend or, over a server.
Data Compression Filters: As the name suggests, You can use data compression filters to compress the data to a certain extent.
Tokenizing Filters: We can store and retrieve all the user data using tokenizing filters.
Encryption Filters: Sometimes, we want to encrypt and save user data that is flowing through the filters. So, encryption filters come into existence and do the job.
Authentication Filters: The authentication filters are employed to accomplish authentication only based on the preset criteria.
As we know, Filters are defined in web.xml, and they are mapped to either servlet or JSP names in your application's deployment descriptor. When the JavaServer Pages container starts up our web application, it creates an instance of each filter that we have declared in the deployment descriptor.
The deployment descriptor can be found in <Tomcat-installation-directory>\conf directory.
JSP Filter Methods
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.
Public void init(FilterConfig):
This method indicates that the filter is placed into service.
Public void destroy():
This method indicates that the filter has been taken out of service.
Filter Example in JSP
In this example, we have created Multiple filters and mapped them in the web.xml filter.
demo.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/htm14/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>demo jsp</title>
</head>
<body>
<%System.out.println("demo jsp...");%>
</body>
</html>
dummyFilter01.java
package com.za.tutorial;
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 DummyFiltere0l implements Filter {
public DummyFilter01() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
System.out.println("DummyFilter01.doFilter...");
chain.doFilter(requet, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
You can also try this code with Online Java Compiler
The sequence of filter-mapping elements in web.xml determines how the web container applies the filter to the JavaServer Pages or servlet. To change the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.
In the above example, we have seen (DummyFilter01)has been executed before(DummyFilter02). We can change the filter execution ordering by changing the filter mapping. If we want to execute (DummyFilter02) before (DummyFilter01), we must change the filter-mapping.
In JavaServer Pages Filter, we can read the init parameters through FilterConfig, which is provided in the initialization method. We can declare an instance variable and map it to the one passed in the init() method.
Q1. What is the difference between interceptor and filter?
Ans:
S.no
Interceptor
Filter
1
It is based on the java reflection mechanism.
It is based on function callback.
2
Interceptor is in a spring container, not depending on the servlet container.
A filter is specified by servlet specification and can only be used in a web program.
3
Interceptors can be called multiple times.
We can only call Filter once when the container is initialized.
Q2. What are the disadvantages of JSP?
Ans: Disadvantages of JSP are:
It is tough to trace JSP pages error because JSP pages are translated to a servlet.
As JSP output is an HTML file, it is not rich in features.
Debugging errors are tough because JSP pages are first translated into servlets before compilation.
Database connectivity is not easy.
Q3. What is Cors filter?
Ans: CORS (Cross-Origin Resource Sharing)Filter is a generic solution for fitting CORS support to Java web applications. Cross-Origin Resource Sharing is a W3C standard for enabling cross-domain requests from web browsers to servers and web APIs that opt in to handle them.
Q4. Why do we use JavaServer Pages instead of HTML?
Ans: JavaServer Pages provides a dynamic interface for the continuously changing data, it dynamically invokes the server actions.
JSP generates dynamic web pages only. In contrast, HTML generated static web pages only. HTML provides a way to give a detailed account of the structure of text-based information in a document.
Key Takeaways
The filters are essential concepts of JavaServer Pages and servlets because it regulates the data flow regarding the client requests based on their needs. It is applicable for servlets mainly, filters are used for building web apps applications.
In his blog, we have discussed JSP filters, filter Methods, and filter examples to clearly understand the concept.