Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Servlet writes filters


May 14, 2021 Servlet


Table of contents


Servlet writes filters

The servlet filter is a Java class that can be used for servlet programming for the following purposes:

  • Block requests from clients before they access back-end resources.
  • These responses are processed before they are sent back to the client by the server.

Various types of filters recommended according to the specification:

  • Authentication Filters.
  • Data compression filters.
  • Encryption filters.
  • Triggers a resource access event filter.
  • Image Conversion Filters.
  • Logging and Auditing Filters.
  • MIME-TYPE Chain Filters.
  • Tagged filters.
  • XSL/T filters (XSL/T Filters) that transform XML content.

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

When a web container launches a web application, it creates an instance for each filter that you declare in the deployment descriptor. The filters are executed in the order in which 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 number Method & Description
1 public void doFilter (ServletRequest, ServletResponse, FilterChain)
The method is called by the container when requesting resources to request resources at the end of the chain at a time a request / response.
2 public void init(FilterConfig filterConfig)
This method is called by the web container, indicating that a filter is placed in service.
3 public void destroy()
This method is called by a web container indicating that a filter is taken out.

FilterConfig is used

A FilterConfig object is provided in Filter's init method.

If the web .xml file is configured as follows:

<filter>
	<filter-name>LoginFilter</filter-name>
	<filter-class>com.w3cschool.test.LogFilter</filter-class>
	<init-param>
		<param-name>Site</param-name>
		<param-value>w3cschool在线教程</param-value>
	</init-param>
	</filter>

Get parameters using the FilterConfig object in the init method:

public void  init(FilterConfig config) throws ServletException {
	// 获取初始化参数
	String site = config.getInitParameter("Site"); 
	// 输出初始化参数
	System.out.println("网站名称: " + site); 
}

An instance of a servlet filter

The following is an example of a servlet filter that outputs the client's IP address and the current date time. This example gives you a basic understanding of servlet filters, and you can write more complex filter applications using the same concepts:

// 导入必需的 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 容器从服务移除之前调用 */
   }
}

This side uses the DisplayHeader example mentioned .java as an example:

//导入必需的 java 库
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")

//扩展 HttpServlet 类
public class DisplayHeader extends HttpServlet {

	// 处理 GET 方法请求的方法
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		// 设置响应内容类型
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();
		String title = "HTTP Header 请求实例 - w3cschool教程实例";
		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 名称</th><th>Header 值</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>");
	}
	// 处理 POST 方法请求的方法
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

Servlet filter mapping in web .xml data (Servlet Filter Mapping)

Define filters, and then map to a URL or servlet, much the same way you define a servlet, and then map to a URL pattern. Create the following entry for the filter .xml in the deployment descriptor file web page:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<filter>
  <filter-name>LogFilter</filter-name>
  <filter-class>com.w3cschool.test.LogFilter</filter-class>
  <init-param>
    <param-name>Site</param-name>
    <param-value>w3cschool在线教程</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>LogFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>  
  <!-- 类名 -->  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- 所在的包 -->  
  <servlet-class>com.w3cschool.test.DisplayHeader</servlet-class>  
</servlet>  
<servlet-mapping>  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- 访问的网址 -->  
  <url-pattern>/TomcatTest/DisplayHeader</url-pattern>  
</servlet-mapping>  
</web-app>  

The above filters apply to all servlets because we specify /* If you only want to apply filters on a few servlets, you can specify a specific servlet path.

Now try calling any servlet in the usual way, and you'll see the logs generated in the Web server. You can also use the Log4J logger to log the above into a separate file.

Use multiple filters

Web applications can define several different filters for a specific purpose. S uppose you define two filters, AuthenFilter and LogFilter. You need to create a different mapping as described below, and the rest is roughly the same as described above:

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>com.w3cschool.test.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>com.w3cschool.test.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 the filters are applied

The .xml filter-mapping elements in the web container determines the order in which filters are applied to the servlet by the web container. To reverse the order of filters, you only need to .xml filter-mapping element in the web filter file.

For example, the example above will apply LogFilter before applying AuthenFilter, but the following instance 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>

The web .xml to configure the node descriptions

Specify a filter.
The filter-name is used to give the filter a name, and the contents of the element cannot be empty.
The element is used to specify the full qualified class name of the filter.
The element is used to specify the initialization parameter for the filter, its child element, the name of the argument, and the value of the parameter.
In the filter, you can use the FilterConfig interface object to access the initialization parameters.
The element is used to set up a resource that Filter is responsible for blocking. A Resource Blocker can be specified in two ways: the servlet name and the request path to the resource access
The child element is used to set the registration name of the filter. The value must be the name of the filter declared in the element
Set the request path blocked by the filter (filter associated URL style)
The name of the servlet intercepted by the filter is specified.
Specify how the resources intercepted by the filter are called by the servlet container, which can be one of REQUEST, INCLUDE, FORWARD, and FORWARDEROR, by default REQUEST. Users can set up multiple child elements to specify how Filter intercepts multiple calls to resources.
The values that child elements can set and their meaning
REQUEST: When the user accesses the page directly, the web container calls the filter. If the target resource is accessed through ThequestDispatcher's include() or forward() method, the filter will not be called.
INCLUDE: If the target resource is accessed through ThequestDispatcher's include() method, the filter is called. Other than that, the filter is not called.
FORWARD: If the target resource is accessed through ThequestDispatcher's forward() method, the filter will be called, except that the filter will not be called.
ERROR: If the target resource is called through a declarating exception handling mechanism, the filter is called. In addition, filters are not called.