Servlet - FilterConfig

Last Updated : 13 May, 2026

FilterConfig is an object created by the web container for each filter to access initialization parameters defined in the web.xml file. It helps separate configuration details from filter implementation, making web applications easier to manage and maintain.

  • Used to read filter initialization parameters from web.xml.
  • Makes filter configuration flexible without changing filter code.

Working of FilterConfig in Servlet Filter

Servlet Filter intercepts incoming HTTP requests and uses FilterConfig during initialization to process configuration details before forwarding the request to the appropriate resource such as a Servlet, JSP, or static file.

Filter
ServletFilter
  • When the client sends an HTTP request, it first reaches the web container.
  • The web container initializes the filter and creates a FilterConfig object.
  • FilterConfig provides configuration details like init parameters and filter name to the filter.
  • The filter executes its logic (e.g., validation, logging, authentication) before request processing.
  • After processing, the filter forwards the request to the target resource (Servlet/JSP/static page).
  • The response is then sent back through the filter chain before reaching the client.

How to Add Filter Configuration in Servlet

There are two approaches to configure FilterConfig in a servlet application using the web.xml deployment descriptor and using annotations with @WebFilter.

1. Using web.xml (Traditional Approach)

In this approach, filter configuration and initialization parameters are defined inside the deployment descriptor using <filter> and <init-param> tags. The container creates the FilterConfig object automatically and passes it to the init() method.

  • Suitable for XML-based servlet applications.
  • Configuration can be changed without modifying source code.
  • Commonly used in older servlet applications.

Syntax:

<filter>
<filter-name>filterName</filter-name>
<filter-class>package.FilterClass</filter-class>
<init-param>
<param-name>paramName</param-name>
<param-value>value</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>filterName</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

2. Using @WebFilter Annotation (Annotation-Based Approach)

Servlet API also allows filter configuration using the @WebFilter annotation. Initialization parameters can be provided using the @WebInitParam annotation.

  • Removes the need for web.xml configuration.
  • Makes configuration simpler and code-centric.
  • Mostly used in modern servlet applications.

Syntax:

@WebFilter(
urlPatterns = "/*",
initParams = {

@WebInitParam(name = "paramName", value = "value")
}
)
public class FilterClass implements Filter {
}

Methods of FilterConfig Interface

The FilterConfig interface provides different methods that help a filter access its configuration details and servlet context information.

1. getFilterName()

This method returns the name of the filter defined in the web.xml file. It is mainly used to identify the current filter during execution.

Syntax:

public String getFilterName() 

2. getInitParameter(String name)

This method is used to get the value of a specific initialization parameter by passing its name. If the parameter is not available, it returns null.

Syntax:

public String getInitParameter(String name)

3. getInitParameterNames()

This method returns all initialization parameter names of the filter as an Enumeration object. It is useful when multiple parameters are configured.

Syntax:

public Enumeration getInitParameterNames()

4. getServletContext()

This method returns the ServletContext object associated with the web application. It allows the filter to access application-wide resources and information.

Syntax:

public ServletContext getServletContext() 

Example To Show How to Add FilterConfig in Servlet

Follow these steps to create Servlet Filter using FilterConfig, where we validate user credentials through initialization parameters defined in web.xml and control request flow using FilterChain.

Step 1: Create Dynamic Web Project

  • Open Eclipse IDE
  • Create a project: FilterConfigDemo
  • Select: Dynamic Web Project
  • Click Finish

Step 2: Create HTML File (index.html)

This is the front-end page where the user enters login credentials. The form sends data to the servlet via POST request.

HTML
<html>
   <head>
       <title>TODO supply a title</title>
       <meta charset="UTF-8">
       <meta name="viewport" content="width=device-width, initial-scale=1.0">
   </head>
  
   <body>
       <h2>FilterConfig Demo</h2>
   <form action="abc" method="post">
       User name <input type="text" name="un"><br>
       Password <input type="password" name="up"><br>
       <input type="submit" value="Login"><input type="reset" value="Clear">
   </form>
   </body>
</html>

Step 3: Create Servlet (abc.java)

This servlet processes the request after filter validation and displays a welcome message.

Java
import static java.lang.System.out;

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

    protected void
    processRequest(HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException
    {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter p = response.getWriter();
        p.println(
            "<font color='red'><h2>Welcome User</h2></font>");
    }

    // <editor-fold defaultstate="collapsed"
    // desc="HttpServlet methods. Click on the + sign on the
    // left to edit the code.">
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo()
    {
        return "Short description";
    }
}

Step 4: Create Filter Class (filter_config_demo.java)

This filter intercepts the request before it reaches the servlet and validates username and password using FilterConfig parameters.

Java
package demo;

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 filter_config_demo implements Filter {

    FilterConfig fc;

    @Override
    public void init(FilterConfig filterConfig)
        throws ServletException
    {
        this.fc = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
        throws IOException, ServletException
    {
        String un, up;
        un = request.getParameter("un");
        up = request.getParameter("up");
        PrintWriter p = response.getWriter();
        System.out.println("My filter Name is "
                          + fc.getFilterName());
        if (un.equals(fc.getInitParameter("username"))
            && up.equals(
                fc.getInitParameter("userpassword")))

        {
            chain.doFilter(request, response);
        }

        else
        {
            RequestDispatcher rd
                = request.getRequestDispatcher(
                    "/index.html");
            rd.include(request, response);
            p.println("incorrect user name and password");
        }
    }

    @Override
    public void destroy()
    {
        this.fc = null;
    }
}

Step 5: Configure web.xml

This file defines servlet mapping, filter mapping, and init parameters required for FilterConfig.

XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html"
         xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html 
                             http://www.oracle.com/webfolder/technetwork/jsc/xml/ns/javaee/index.html/web-app_3_1.xsd">

   <filter>
       <filter-name>filter1</filter-name>
       <filter-class>demo.filter_config_demo</filter-class>
       <init-param>
           <param-name>username</param-name>
           <param-value>sumit</param-value>
       </init-param>

       <init-param>
           <param-name>userpassword</param-name>
           <param-value>sumit@123</param-value>
       </init-param>
   </filter>

   <filter-mapping>
       <filter-name>filter1</filter-name>
       <servlet-name>abc</servlet-name>
   </filter-mapping>

   <servlet>
       <servlet-name>abc</servlet-name>
       <servlet-class>abc</servlet-class>
   </servlet>

   <servlet-mapping>
       <servlet-name>abc</servlet-name>
       <url-pattern>/abc</url-pattern>
   </servlet-mapping>

   <session-config>
       <session-timeout>30</session-timeout>
   </session-config>

</web-app>

Step 6: Run the Project

  • Right click project -> Run As -> Run on Server
  • Open browser:

http://localhost:8080/FilterConfigDemo/index.html

Output

Your Login page will appear on the browser

First, we entered the wrong user id and password

  • user id - admin
  • password - 12345

When incorrect credentials are provided, the filter handles the response by reloading the login page and displaying an error message.

Now we entered the Correct user id and password:

  • user id - sumit
  • password - sumit@123

When user provides correct credential then the servlet executes and generates response output

Explanation: When the user submits the login form, the request first passes through the Filter, where credentials are validated using FilterConfig parameters from web.xml. If valid, the request is forwarded to the servlet using chain.doFilter(); otherwise, the login page is reloaded with an error message.

Comment