Latest web development tutorials

Servlet Writing Filters

Servlet filters can be dynamically intercepts the request and response in order to transform or use the information contained in the request or response.

One or more Servlet filters can be attached to a Servlet or a Servlet. Servlet filters can also be attached to the JavaServer Pages (JSP) files and HTML pages. Calling all additional Servlet filters before calling Servlet.

Servlet filters are available for the Java Servlet programming class, you can achieve the following objectives:

  • Before requesting access to back-end resources, client intercept these requests.
  • Before the server sends the response back to the client to deal with these responses.

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

  • Authentication filter (Authentication Filters).
  • Data compression filter (Data compression Filters).
  • Encryption Filters (Encryption Filters).
  • Resource Access trigger event filter.
  • Image conversion filters (Image Conversion Filters).
  • Logging and auditing filters (Logging and Auditing Filters).
  • MIME-TYPE chain filter (MIME-TYPE Chain Filters).
  • Labeled filter (Tokenizing Filters).
  • XSL / T filter (XSL / T Filters), transforming XML content.

Filter deployment descriptor (web.xml) in XML tags via the Web statement, and then mapped to your application's deployment descriptor Servlet name or URL pattern.

When the Web container to start a Web application, it will be for you in the deployment descriptor declaration for each filter to create an instance.

Filter execution order is consistent with the order of arrangement in the web.xml configuration file, usually the Filter configuration before all Servlet.

Servlet Filter Method

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

序号方法 & 描述
1public void doFilter (ServletRequest, ServletResponse, FilterChain)
该方法完成实际的过滤操作,当客户端请求方法与过滤器设置匹配的URL时,Servlet容器将先调用过滤器的doFilter方法。FilterChain用户访问后续过滤器。
2public void init(FilterConfig filterConfig)
web 应用程序启动时,web 服务器将创建Filter 的实例对象,并调用其init方法,读取web.xml配置,完成对象的初始化功能,从而为后续的用户请求作好拦截的准备工作(filter对象只会创建一次,init方法也只会执行一次)。开发人员通过init方法的参数,可获得代表当前filter配置信息的FilterConfig对象。
3public void destroy()
Servlet容器在销毁过滤器实例前调用该方法,在该方法中释放Servlet过滤器占用的资源。

FilterConfig use

Filter's init method provides a FilterConfig object.

Web.xml file configuration as follows:

<filter>
	<filter-name>LoginFilter</filter-name>
	<filter-class>com.w3big.test.LogFilter</filter-class>
	<init-param>
		<param-name>Site</param-name>
		<param-value>本教程</param-value>
	</init-param>
	</filter>

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

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

Servlet filter instance

The following are examples of Servlet filters, output name and website address. The Servlet examples to give you a basic understanding of the filter, you can use the same concept to write more complex filter applications:

package com.w3big.test;

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

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

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

		// 输出站点名称
		System.out.println("站点网址:http://www.w3big.com");

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

Here the use of the previously mentioned DisplayHeader.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 请求实例 - 本教程实例";
		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);
	}
}

Web.xml the Servlet filter mapping (Servlet Filter Mapping)

Define filters, then mapped to a URL or Servlet, which define the Servlet, and then mapped to a URL pattern much the same way. Create the following entry for the filter tag in the deployment descriptor fileweb.xml:

<?xml version="1.0" encoding="UTF-8"?>  
<web-app>  
<filter>
  <filter-name>LogFilter</filter-name>
  <filter-class>com.w3big.test.LogFilter</filter-class>
  <init-param>
    <param-name>Site</param-name>
    <param-value>本教程</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.w3big.test.DisplayHeader</servlet-class>  
</servlet>  
<servlet-mapping>  
  <servlet-name>DisplayHeader</servlet-name>  
  <!-- 访问的网址 -->  
  <url-pattern>/TomcatTest/DisplayHeader</url-pattern>  
</servlet-mapping>  
</web-app>  

The filter applies to all Servlet, because we specified in the configuration/ *.If you want to apply a filter on a small number of Servlet, you can specify a specific Servlet path.

Now try the usual manner to call any Servlet, you will see the generated Web server logs. You can also use the recorder to the above Log4J logging to a separate file.

Next we visit this instance address http: // localhost: 8080 / TomcatTest / DisplayHeader, then look at the output in the console, as follows:

Using a plurality of filters

Web applications can be several different filters based on the specific purpose defined. Suppose you have defined two filtersAuthenFilterandLogFilter.You need to create a different mapping described below, and above the rest of the process is substantially the same explanation:

<Filter>
   <Filter-name> LogFilter </ filter-name>
   <Filter-class> com.w3big.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.w3big.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>

Filters are applied sequentially

Order in web.xml filter-mapping element determines the Web container to apply filters to the order of the Servlet. To reverse the order of the filter, you only need to reverse the filter-mapping element in the web.xml file.

For example, the above example will be the first application LogFilter, then apply AuthenFilter, but the following examples 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>

web.xml configuration instructions for each node

  • <filter> Specifies a filter.
    • <filter-name> is used to specify a name for the filter, the content of the element can not be empty.
    • <filter-class> element is used to specify the fully qualified class name of the filter.
    • <init-param> element is used to specify initialization parameters for the filter, its child elements <param-name> specifies the name of the parameter, <param-value> value specified parameters.
    • In the filter, you can use FilterConfig interface object to access the initialization parameters.
  • <filter-mapping> element is used to set a Filter resource responsible intercepted. Filter intercept a resource can be specified in two ways: the request path Servlet name and resource access
    • <filter-name> child element is used to set the registered name of the filter. The value must be in the <filter> element declarations in the name of the filter through
    • <url-pattern> set filter intercepted request path (filter associated URL style)
  • <servlet-name> Specifies the filter blocked Servlet name.
  • <dispatcher> specify the filter intercepted resources are called Servlet containers, which can be REQUEST , INCLUDE , FORWARD and ERROR one default REQUEST . Users can set up multiple <dispatcher> sub-element is used to specify the resource Filter multiple ways to intercept calls.
  • <dispatcher> value and significance of sub-elements that can be set
    • REQUEST : When the user direct access to pages, Web container will call the filter. If the target is a method to access the resource, then the filter will not be called by the RequestDispatcher's include () or forward ().
    • INCLUDE : If the target resource is accessed via the RequestDispatcher's include (), then the filter will be called. In addition, the filters will not be called.
    • FORWARD : If the target resource is accessed through a RequestDispatcher forward () method, then the filter will be called, in addition, the filter will not be called.
    • ERROR : If the target resource is through declarative exception handling mechanism called, then the filter will be called. In addition, the filter will not be called.