Servlet writing filter


Servlet filters are Java classes that can be used in Servlet programming and have the following purpose:

  • Intercept client requests before they access back-end resources.

  • Handle the server's responses before they are sent back to the client.

Various types of filters recommended according to the specification:

  • Authentication Filters.

  • Data compression Filters.

  • Encryption Filters.

  • Trigger resource access event filter.

  • Image Conversion Filters.

  • Logging and Auditing Filters.

  • MIME-TYPE Chain Filters.

  • Tokenizing Filters.

  • XSL/T Filters (XSL/T Filters), convert XML content.

Filters are deployed in the deployment descriptor file web.xml and are then mapped to the Servlet name or URL pattern in your application's deployment descriptor .

When the web container starts a web application, it creates an instance for each filter you declare in the deployment descriptor. The filters are executed in the order they are declared in the deployment descriptor.

Servlet filter method

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

Serial NumberMethod & Description
1 public void doFilter (ServletRequest, ServletResponse, FilterChain)
This method is passed every time a request/response pair is passed through the chain due to the client requesting resources at the end of the chain. Container call.
2public void init(FilterConfig filterConfig)
This method is called by the Web container to indicate that a filter is put into the service .
3public void destroy()
This method is called by the web container to indicate that a filter is taken out of service.

Servlet filter example

The following is an example of the Servlet filter, which will output the client's IP address and the current date and time. This example gives you a basic understanding of Servlet filters, and you can use the same concepts to write more complex filter applications:

// 导入必需的 java 库
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// 实现 Filter 类
public class LogFilter implements Filter  {
   public void  init(FilterConfig config) 
                         throws ServletException{
      // 获取初始化参数
      String testParam = config.getInitParameter("test-param"); 

      // 输出初始化参数
      System.out.println("Test Param: " + testParam); 
   }
   public void  doFilter(ServletRequest request, 
                 ServletResponse response,
                 FilterChain chain) 
                 throws java.io.IOException, ServletException {

      // 获取客户机的 IP 地址   
      String ipAddress = request.getRemoteAddr();

      // 记录 IP 地址和当前时间戳
      System.out.println("IP "+ ipAddress + ", Time "
                                       + new Date().toString());

      // 把请求传回过滤链
      chain.doFilter(request,response);
   }
   public void destroy( ){
      /* 在 Filter 实例被 Web 容器从服务移除之前调用 */
   }
}

Compile LogFilter.java in the usual way, Place your class files in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.

Servlet Filter Mapping in Web.xml

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

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
	  <param-name>test-param</param-name>
	  <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

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

Now try to call any Servlet in the usual way and you will see the logs generated in the web server. You can also use the Log4J logger to log the above to a separate file.

Using Multiple Filters

Web applications can define several different filters based on 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 process is roughly the same as explained above:

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
	  <param-name>test-param</param-name>
	  <param-value>Initialization Paramter</param-value>
   </init-param>
</filter>

<filter>
   <filter-name>AuthenFilter</filter-name>
   <filter-class>AuthenFilter</filter-class>
   <init-param>
	  <param-name>test-param</param-name>
	  <param-value>Initialization Paramter</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>

The order in which filters are applied

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

For example, the above example will apply the LogFilter first and then the 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>