JSP filter


Filters in Servlets and JSPs are Java classes. Their purpose of existence is as follows:

  • Interception when requesting access to back-end resources

  • Manage responses returned from the server to the client

A variety of commonly used filter types are listed below:

  • Authentication filter

  • Data compression filter

  • Encryption filter

  • Trigger resource access Filters for Events

  • Image Conversion Filters

  • Login and Authentication Filters

  • MIME Type chain filter

  • Token filter

  • XSL/T filter that converts XML content

The filter will be inserted into the web.xml file and then map the name of the servlet, JSP file, or URL pattern. The deployment description file web.xml can be found in the <Tomcat-installation-directory>\conf directory.

When the JSP container starts a network application, it will create an instance of each filter. These filters must be declared in the deployment descriptor file web.xml and executed in the order of declaration.


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
1public void doFilter (ServletRequest, ServletResponse, FilterChain)


The container will call this method whenever a request/response passes through the filter chain, because the client requests the resource at the end of the chain
2public void init(FilterConfig filterConfig)


The container calls this method to indicate that a filter is placed in the service
3 public void destroy()


The container calls this method to indicate that a filter is being removed from the service

JSP filter example

This example will print the IP address and the date and time of each access to the JSP file. Of course, this is just a simple example to give you some idea of ​​simple filter usage, but you can use these concepts to construct more complex programs on your own.

//  引入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实例在服务器上被移除前调用。*/
   }
}

Compile the LogFilter.java file, and then place the compiled class file in the <Tomcat installation directory>/webapps/ROOT/WEB-INF/classes directory.


JSP filter mapping in the web.xml file

Filters are defined and then mapped to a URL or JSP file name, similar to how a servlet is defined and then mapped. In the deployment description file web.xml, use the <filter> tag for filter mapping:

<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 will be applied to all servlets and JSP programs because we specified " /*". You can also specify a servlet or JSP path if you only want to apply the filter to a few servlets or JSP programs.


Now, access the servlet or JSP page as usual, and you will find that a record of this access is generated in the server log. You can also use the Log4J logger to log to other files.


Using multiple filters

Your web application can define many different filters. Now that you have two filters defined, AuthenFilter and LogFilter, the other steps are the same as before, except you want to create a different mapping, like this:

<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>

Filter Application Order

The mapping order of the <filter> elements in web.xml determines the order in which the container applies these filters. To reverse the order of application, you simply reverse the order in which the <filter> elements are defined in web.xml.

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

<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>