Filter Mapping in Web.xml

โšก Smart Summary

Filter Mapping in Web.xml defines how JSP filters intercept client requests and server responses in a Java web application. It registers each filter in the deployment descriptor, enabling authentication, logging, compression, and encryption before resources are accessed.

  • ๐Ÿงฉ Filter Defined: A web.xml component that filters requests and responses in a Java web application.
  • ๐Ÿ” Filter Types: Authentication, data compression, encryption, MIME chain, logging, and tokenizing filters.
  • โš™๏ธ Lifecycle Methods: init() starts the filter, doFilter() runs per request, and destroy() removes it from service.
  • ๐Ÿ—บ๏ธ Mapping: The filter and filter-mapping tags link a filter class to a URL pattern in web.xml.
  • ๐Ÿงช Example: GuruFilter logs the client IP, date, and time, then passes the request along the filter chain.

Filter Mapping in Web.xml

What is JSP Filters?

  • Filters in web.xml are used for filtering functionality of the Java web application.
  • They intercept the requests from client before they try to access the resource.
  • They manipulate the responses from the server and sent to the client.

Filters are defined in web.xml, and they are a map to servlet or JSP. When JSP container starts with the web application, it creates the instance of each filter in web.xml that have been declared in the deployment descriptor.

Types of Filters in JSP

JSP supports several filter types, each handling a specific concern in the request-response cycle:

  • Authentication filters
  • Data compression filters
  • Encryption filters
  • MIME chain filters
  • Logging Filters
  • Tokenizing filters

JSP Filter Methods

Once you know the filter types, it helps to understand the methods that control a filter’s lifecycle. Following are the filter methods:

Public void doFilter(ServletRequest, ServletResponse, FilterChain)

This is called everytime when a request/response is passed from every client when it is requested from a resource.

Public void init(FilterConfig)

This is to indicate that filter in JSP is placed into service.

Public void destroy()

This to indicate the filter has been taken out from service.

Example

In this example, we have created filter and mapped in Java web.xml filter.

Gurufilter.java

package demotest;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


public class GuruFilter implements Filter {

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        HttpServletRequest req = (HttpServletRequest) request;


        String ipAddress = req.getRemoteAddr();
        System.out.println("IP Address "+ipAddress + ", Time is"
                            + new Date().toString());

        // pass the request along the filter chain
        chain.doFilter(request, response);
    }

    /**
    * @see Filter#init(FilterConfig)
    */
    public void init(FilterConfig fConfig) throws ServletException {
    String guruparam = fConfig.getInitParameter("guru-param");

    //Print the init parameter
    System.out.println("Test Param: " + guruparam);
    }
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>
    test</display-name>
    <filter>
        <description>
        </description>
        <display-name>
        GuruFilter</display-name>
        <filter-name>GuruFilter</filter-name>
        <filter-class>demotest.GuruFilter</filter-class>
        <init-param>
        <param-name>guru-param</param-name>
        <param-value>This is guru paramter</param-value>
    </init-param>
    </filter>
    <filter-mapping>
       <filter-name>GuruFilter</filter-name>
       <url-pattern>/GuruFilter</url-pattern>
    </filter-mapping>

Explanation of the code

Gurufilter.java

Code Line 17-32: Here we are using “doFilter” method where we are getting request object (in our example the request object is req (HttpServletRequest object)) and get the remote address of the client and printing on the console and also printing date and time on the console.

Code Line 33-37: Here we are using init method where we are taking the init parameter and printing init parameter in the console.

Web.xml

Code Line 10-11: Filter mapping in web.xml for GuruFilter with the class name GuruFilter.java where we have filter-name as GuruFilter and filter class which is directory path of GuruFilter class.

Code Line 13-15: Mapping the init parameter named guru-param and getting the value of it which is placed under filter tag so this init-param has been defined for gurufilter.

Output:

When you execute the above code, you get the following output:

JSP Filter Methods

  • The output is Test Param from the init parameter
  • And fetching IP address, date and time of it.

FAQs

A servlet handles and generates a response for a request, while a filter intercepts requests and responses to perform pre-processing or post-processing such as authentication or logging, without producing the final response itself.

Filters execute in the order their filter-mapping entries appear in web.xml. The container chains them, so the first mapped filter runs first on the request and last on the response.

A JSP filter has three lifecycle methods: init() to initialize the filter, doFilter() to process each request and response, and destroy() to release resources when the filter is removed from service.

AI can analyze stack traces, detect incorrect filter-mapping order, suggest missing init parameters, and spot performance bottlenecks in doFilter logic, helping developers resolve filter issues faster during testing and code review.

Yes. AI can generate web.xml filter and filter-mapping entries from a description of the desired behavior, including URL patterns and init parameters, which developers then review and adjust for their application.

Summarize this post with: