14 - Servlet Filters: Page 3 of 3

14.6.4 Write a filter example to read all the init parameters and display them on  screen

Solution- Define a filter with two init params which filter will read and display. As in servlets, init parameter  can be read through Servlet config object, similarly in filter we can read the init parameter through FilterConfig.

Servlet has a convenient method getServletConfig() available but in filter there is no such method available.

Filters provides  FilterConfig object in initialization method so we can define a instance variable and map it to the one passed in init() method. Refer highlighted section in  below code for more details.

  1. Add entry in web.xml

  1. Write Filter Code
package com.servlet.tutorial;
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 DisplayInitParamFilter implements Filter {
private FilterConfig filterConfig=null;
public void init(FilterConfig filterConfig) throws ServletException {
    System.out.println("Filter  initialized...");
    this.filterConfig = filterConfig;
public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
Enumeration<String> initParams= filterConfig.getInitParameterNames();
StringBuffer buffer = new StringBuffer();
    String initParamName = initParams.nextElement();
    String initParamValue =filterConfig.getInitParameter(initParamName);
    buffer.append(initParamName+"::" + initParamValue);
PrintWriter writer = response.getWriter();
public void destroy() {
    System.out.println("Filter  Destroyed..");


Hit the url http://localhost:8080/HelloWorld/input.html and enter some value. In  earlier example we created input.html so if we enter some value and submit it will pass the Interceptor filter and will execute the DisplayInitParamFilter

Like us on Facebook