An object of FilterConfig is created by the web container. This object can be used to get the configuration information from the web.xml file.

Methods of FilterConfig interface

There are following 4 methods in the FilterConfig interface.

  1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
  2. public String getInitParameter(String parameterName): Returns the parameter value for the specified parameter name.
  3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter names.
  4. public ServletContext getServletContext(): Returns the ServletContext object.

Example of FilterConfig

In this example, if you change the param-value to no, request will be forwarded to the servlet otherwise filter will create the response with the message: this page is underprocessing. Let’s see the simple example of FilterConfig. Here, we have created 4 files:

  • index.html
  • MyFilter.java
  • HelloServlet.java
  • web.xml

index.html

MyFilter.java

import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.*;  
  
public class MyFilter implements Filter{  
FilterConfig config;  
  
public void init(FilterConfig config) throws ServletException {  
    this.config=config;  
}  
  
public void doFilter(ServletRequest req, ServletResponse resp,  
    FilterChain chain) throws IOException, ServletException {  
      
    PrintWriter out=resp.getWriter();  
          
    String s=config.getInitParameter("construction");  
          
    if(s.equals("yes")){  
         out.print("This page is under construction");  
    }  
    else{  
         chain.doFilter(req, resp);//sends request to next resource  
    }  
          
}  
public void destroy() {}  
}

HelloServlet.java

import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
  
public class HelloServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
      
        out.print("
welcome to servlet
");  
          
    }  
  
}

web.xml

  
  
   
    HelloServlet  
    HelloServlet  
    
  
    
    HelloServlet  
    /servlet1  
    
    
    
  f1  
  MyFilter  
    
  construction  
  no  
    
    
    
  f1  
  /servlet1