![]() |
VOOZH | about |
A Servlet Filter Chain is a sequence of filters that are applied to a web resource (Servlet, JSP, or HTML page) before and after the request is processed. It allows multiple filters to work together to handle and modify requests and responses in a structured order.
The below diagram illustrates the working flow of a Servlet Filter Chain, showing how a client request passes through multiple filters before reaching the servlet and how the response returns back through the same chain.
To create a filter class, we must implement the methods of the javax.servlet.Filter interface. These methods are used to initialize, process requests/responses, and destroy the filter object.
This method is called by the web container only once when the filter is created. It is used to initialize filter configuration parameters and allocate required resources.
public void init(FilterConfig config) throws ServletException
{
// initialization code
}
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)This method is called whenever a client requests a web resource such as a Servlet or JSP page. It is mainly used for request preprocessing and response postprocessing.
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// request preprocessingchain.doFilter(request, response);
// response postprocessing
}
This method is called before removing the filter object from service. It is used to release resources and perform cleanup operations.
public void destroy()
{
// cleanup code
}
This example demonstrates how to create and run a Servlet Filter Chain application using two filters and one servlet.
After completion of above steps the Project created in the Eclipse Working directory and project Directory looks like:
👁 ImageThis page accepts user input and After clicking submit, the request goes to GfgServlet.
This filter executes first in the filter chain and processes the client request before passing it to the next filter.
This filter executes after GfgFilter1 and forwards the processed request to the target servlet.
This servlet executes after all filters complete request processing and generates the final response.
Defines filter configuration and execution order and Maps servlet and filters with URL pattern.
http://localhost:8080/ServletFilterchain/index.html
Your Login page will appear on the browser
👁 OutputClick on the submit button and the following screen output will be shown.
👁 OutputExplanation: When the user clicks the submit button, the request first passes through Filter1 and then Filter2 before reaching the servlet. After the servlet executes, the response returns in reverse order through Filter2 and Filter1, and the final output is displayed in the browser.