English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Servlet Writing Filters

Servlet filters can dynamically intercept requests and responses to transform or use information contained in the request or response.

One or more Servlet filters can be attached to a Servlet or a group of Servlets. Servlet filters can also be attached to JavaServer Pages (JSP) files and HTML pages. All attached Servlet filters are called before the Servlet is called.

Servlet filters are Java classes available for Servlet programming that can achieve the following purposes:

  • Intercept these requests before the client accesses the backend resources.

  • Process these responses before sending them back to the client.

According to the various types of filters recommended by the specifications:

  • Authentication Filters).

  • Data compression Filters).

  • Encryption Filters).

  • Trigger resource access event filter.

  • Image Conversion Filters).

  • Logging and Auditing Filters).

  • MIME-TYPE Chain Filters (MIME-TYPE Chain Filters).

  • Tokenizing Filters).

  • XSL/T Filter (XSL/T Filters), transform XML content.

Filters are declared through the XML tags in the Web deployment descriptor (web.xml) and then mapped to the Servlet name or URL pattern in the application's deployment descriptor.

When the Web container starts the Web application, it will create an instance for each filter declared in the deployment descriptor.

The execution order of the Filter is consistent with the configuration order in the web.xml configuration file, and it is generally recommended to configure the Filter before all Servlets.

Servlet Filter Methods

A filter is a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods:

Serial NumberMethod & Description
1public void doFilter(ServletRequest, ServletResponse, FilterChain)
This method completes the actual filtering operation. When the client request method matches the URL set by the filter, the Servlet container will first call the doFilter method of the filter. The FilterChain is used to access subsequent filters.
2public void init(FilterConfig filterConfig)
When the web application starts, the web server will create an instance of the Filter and call its init method to read the web.xml configuration, complete the initialization of the object, and prepare for subsequent user requests by intercepting the preparations (the filter object will only be created once, and the init method will only be executed once). Developers can obtain the FilterConfig object representing the current filter configuration through the parameters of the init method.
3public void destroy()
The Servlet container calls this method before destroying the filter example, and in this method, release the resources occupied by the Servlet filter.

FilterConfig uses

The init method of the Filter provides a FilterConfig object.

As configured in the web.xml file as follows:

<filter>
    <filter-name>LogFilter</filter-name>
    <filter-class>com.w3codebox.test.LogFilter</filter-class>
    <init-param>
        <param-name>Site</param-name>
        <param-value>Basic Tutorial Website</param-value>
    </init-param>
</filter>

Use the FilterConfig object to get parameters in the init method:

public void init(FilterConfig config) throws ServletException {
    // Get initialization parameters
    String site = config.getInitParameter("Site"); 
    // Output initialization parameters
    System.out.println("Website Name: "" + site); 
}

Servlet Filter Example

Below is an example of a Servlet filter, which will output the website name and address. This example gives you a basic understanding of Servlet filters, and you can use the same concepts to write more complex filter application programs:

package com.w3codebox.test;
//Import the necessary java library
import javax.servlet.*;
import java.util.*;
//Implement the Filter class
public class LogFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        // Get initialization parameters
        String site = config.getInitParameter("Site"); 
        // Output initialization parameters
        System.out.println("Website Name: "" + site); 
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException {
        // Output the site name
        System.out.println("Site URL: http:")//www.oldtoolbag.com");
        // Pass the request back to the filter chain
        chain.doFilter(request,response);
    }
    public void destroy( ){
        /* Call before the Filter example is removed from the service by the Web container */
    }
}

Here we use the DisplayHeader.java mentioned earlier as an example:

//Import the necessary java library
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DisplayHeader)
//Extends HttpServlet class
public class DisplayHeader extends HttpServlet
    // Method to handle GET method requests
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // Set response content type
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String title = "HTTP Header Request Example - Basic Tutorial Website Example";
        String docType =
            "<!DOCTYPE html> \n";
            out.println(docType +
            "<html>\n" +
            "<head><meta charset="utf-8">><title>" + title + "</title></head>\n"+
            "<body bgcolor="#f0f0f0">\n" +
            "<h1 align="center">" + title + "</h1>\n" +
            "<table width="100%" border="1" align="center">\n" +
            "<tr bgcolor="#949494\">\n" +
            "<th>Header name</th><th>Header value</th>\n"+
            "</tr>\n");
        Enumeration headerNames = request.getHeaderNames();
        while(headerNames.hasMoreElements()) {
            String paramName = (String)headerNames.nextElement();
            out.print("<tr><td>" + paramName + "</td>\n");
            String paramValue = request.getHeader(paramName);
            out.println("<td>  " + paramValue + "</td></tr>\n");
        }
        out.println("</table>\n</body></html>");
    }
    // Method to handle POST method requests
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Servlet Filter Mapping in Web.xml

Define a filter and then map it to a URL or Servlet, which is roughly the same as defining a Servlet and then mapping it to a URL pattern. In the deployment descriptor file web.xml Create the following entry for the filter tag in

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<filter>
  <filter-name>LogFilter</filter-name>
  <filter-class>com.w3codebox.test.LogFilter</filter-class>
  <init-param>
    <param-name>Site</param-name>
    <param-value>Basic Tutorial Website</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>LogFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>  
  <!-- Class name -->  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- in the package -->  
  <servlet-class>com.w3codebox.test.DisplayHeader</servlet-class>  
</servlet>  
<servlet-mapping>  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- The URL visited -->  
  <url-pattern>/TomcatTest/DisplayHeader</url-pattern>  
</servlet-mapping>  
</web-app>

The above filter applies to all Servlets because we specify in the configuration /* . If you only want to apply the filter to a few Servlets, you can specify a specific Servlet path.

Now try to call any Servlet in a common way, you will see the log generated in the Web server. You can also use Log4J Recorder to record the above log into a separate file.

Next, we visit this example address http://localhost:8080/TomcatTest/DisplayHeader, and then check the output content on the console, as shown below:

Use multiple filters

A web application can define several different filters for specific purposes. Suppose you define two filters AuthenFilter and LogFilter.You need to create a different mapping as described below, and the rest of the processing is roughly the same as what was explained above:

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>com.w3codebox.test.LogFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
<filter>
   <filter-name>AuthenFilter</filter-name>
   <filter-class>com.w3codebox.test.AuthenFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Parameter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

Application order of filters

filter in web.xml-The order of the mapping element determines the order in which the Web container applies the filter to the Servlet. To reverse the order of the filters, you only need to reverse the filter in the web.xml file-mapping element is enough.

For example, the above example will first apply LogFilter, and then apply AuthenFilter, but the following example will reverse this order:

<filter-mapping>
   <filter-name>AuthenFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

Description of each node in web.xml configuration

  • <filter>Specify a filter.

    • <filter-name>Used to specify a name for the filter, the content of this element cannot be empty.

    • <filter-class>element is used to specify the complete qualified name of the filter.

    • <init-param>element is used to specify initialization parameters for the filter, its child element <param-name>Specify the name of the parameter, <param-value>Specify the value of the parameter.

    • In the filter, the FilterConfig interface object can be used to access initialization parameters.

  • <filter-The mapping element is used to set the resources that a Filter is responsible for intercepting. The resources intercepted by a Filter can be specified in two ways: Servlet name and the request path of resource access

    • <filter-The child element is used to set the registration name of the filter. This value must be the name of a filter declared in the <filter> element.

    • <url-pattern>sets the request path intercepted by the filter (the URL pattern associated with the filter)

  • <servlet-name>specifies the name of the Servlet intercepted by the filter.

  • <dispatcher> specifies the way the Servlet container invokes the resources intercepted by the filter, which can be one of REQUEST, INCLUDE, FORWARD, and ERROR, with REQUEST being the default. Users can set multiple <dispatcher> sub-elements to specify multiple intercepting ways for Filter to resources.

  • The values that can be set for the <dispatcher> sub-element and their meanings

    • REQUEST: When the user directly accesses the page, the web container will call the filter. If the target resource is accessed through the RequestDispatcher's include() or forward() method, then the filter will not be called.

    • INCLUDE: If the target resource is accessed through the RequestDispatcher's include() method, then this filter will be called. Otherwise, the filter will not be called.

    • FORWARD: If the target resource is accessed through the RequestDispatcher's forward() method, then this filter will be called, otherwise, the filter will not be called.

    • ERROR: If the target resource is called through the declarative exception handling mechanism, then this filter will be called. Otherwise, the filter will not be called.