1. Introduction to Filter
Filter is also called a filter. It is the most exciting technology in Servlet technology. Through Filter technology, WEB developers intercept all web resources managed by web servers: such as Jsp, Servlet, static image files or static html files, thereby achieving some special functions. For example, implement some advanced functions such as URL-level permission access control, filtering sensitive vocabulary, and compressing response information.
The Servlet API provides a Filter interface. When developing web applications, if the written Java class implements this interface, the Java class is called the filter Filter. Through Filter technology, developers can implement users' access requests and responses before accessing a target resource, as shown below:
2. How does Filter intercept?
There is a doFilter method in the Filter interface. When we write Filter and configure which web resource to intercept, the WEB server will call the doFilter method of filter every time before calling the service method of the web resource. Therefore, writing code in this method can achieve the following purpose:
1. Let a piece of code execute before calling the target resource.
2. Whether to call the target resource (that is, whether to allow users to access the web resource).
3. After calling the target resource, let a piece of code execute.
When the web server calls the doFilter method, it will pass a filterChain object in. The filterChain object is the most important object in the filter interface. It also provides a doFilter method. Developers can decide whether to call this method according to their needs. If this method is called, the web server will call the service method of the web resource, that is, the web resource will be accessed, otherwise the web resource will not be accessed.
3. Getting started with Filter development
3.1. Filter development steps
Filter development is divided into two steps:
1. Write a java class to implement the Filter interface and implement its doFilter method.
2. Use the <filter> and <filter-mapping> elements in the web.xml file to register the written filter class and set the resources it can intercept.
Filter example:
package me.gacl.web.filter;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;/*** @ClassName: FilterDemo* @Description:Three typical applications of filter: * , you can decide whether to call chain.doFilter(request, response) method, *, that is, whether to let the target resource be executed*, before let the target resource be executed, you can preprocess the request/response, and then let the target resource be executed*, and after the target resource is executed, the execution result of the target resource can be captured, thereby realizing some special functions* @author: 小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小小� response,FilterChain chain) throws IOException, ServletException {//Please some preprocessing on request and response request.setCharacterEncoding("UTF-");response.setCharacterEncoding("UTF-");response.setContentType("text/html;charset=UTF-");System.out.println("FilterDemo before execution!!!");chain.doFilter(request, response); //Let the target resource execute and release System.out.println("FilterDemo after execution! ! ! ");}@Overridepublic void destroy() {System.out.println("----Filter Destruction----");}} Configure filters in web.xml:
<?xml version="." encoding="UTF-"?><web-app version="." xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w.org//XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app__.xsd"><display-name></display-name> <welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!--Configuration filter--><filter><filter-name>FilterDemo</filter-name><filter-class>me.gacl.web.filter.FilterDemo</filter-class></filter><!--Mapping filter--><filter-mapping><filter-name>FilterDemo</filter-name><!--"/*" means intercepting all requests--><url-pattern>/*</url-pattern></filter-mapping></web-app>
3.2. Filter chain
In a web application, multiple Filters can be developed and written, which are combined into one Filter chain.
The web server decides which Filter to call first according to the order in which Filter is registered in the web.xml file. When the doFilter method of the first Filter is called, the web server will create a FilterChain object representing the Filter chain and pass it to the method. In the doFilter method, if the developer calls the doFilter method of the FilterChain object, the web server will check whether there is still a filter in the FilterChain object. If there is, the second filter is called, and if there is no, the target resource is called.
4. The life cycle of Filter
4.1. Creation of Filter
The creation and destruction of Filter is the responsibility of the WEB server. When the web application is started, the web server will create an instance object of Filter and call its init method to complete the initialization function of the object, thereby preparing for interception for subsequent user requests. The filter object will only be created once, and the init method will only be executed once. Through the parameters of the init method, a FilterConfig object representing the current filter configuration information can be obtained.
4.2. Destruction of Filter
The web container calls the destroy method to destroy the Filter. The destroy method is executed only once during the life cycle of the Filter. In the destroy method, the resources used by the filter can be freed.
4.3. FilterConfig interface
When configuring filters, users can use <init-param> to configure some initialization parameters for filters. When the web container instantiates the Filter object and calls its init method, the filterConfig object encapsulating the filter initialization parameters will be passed in. Therefore, when developers write filters, they can obtain:
String getFilterName(): Get the name of the filter.
String getInitParameter(String name): Returns the value of the initialization parameter with the name specified in the deployment description. Return null if it does not exist.
Enumeration getInitParameterNames(): Returns an enumeration set of names of all initialization parameters of the filter.
public ServletContext getServletContext(): Returns a reference to the Servlet context object.
Example: Use FilterConfig to obtain filter configuration information
package me.gacl.web.filter;import java.io.IOException;import java.util.Enumeration;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;public class FilterDemo implements Filter {/* Filter initialization* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)*/@Overridepublic void init(FilterConfig filterConfig) throws ServletException {System.out.println("----Filter Initialization----");/*** <filter><filter-name>FilterDemo</filter-name><filter-class>me.gacl.web.filter.FilterDemo</filter-class><!--Configure initialization parameters of FilterDemo filter--><init-param><description>Configure initialization parameters of FilterDemo filter</description><param-name>name</param-name><param-value>gacl</param-value></init-param><init-p aram><description>Configure the initialization parameters of FilterDemo filter</description><param-name>like</param-name><param-value>java</param-value></init-param></filter><filter-mapping><filter-name>FilterDemo</filter-name><!--"/*" means intercepting all requests--><url-pattern>/*</url-pattern></filter-mapping>*/// Get the filter's name String filterName = filterConfig.getFilterName();//Get the initialization parameter configured in the web.xml file String initParam = filterConfig.getInitParameter("name"); String initParam = filterConfig.getInitParameter("like");//Returns an enumeration set of names of all initialization parameters of the filter. Enumeration<String> initParameterNames = filterConfig.getInitParameterNames();System.out.println(filterName);System.out.println(initParam);System.out.println(initParam);System.out.println(initParam); while (initParameterNames.hasMoreElements()) {String paramName = (String) initParameterNames.nextElement();System.out.println(paramName);}}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {System.out.println("FilterDemo before execution!!!"); chain.doFilter(request, response); //Let the target resource be executed and System.out.println("FilterDemo after execution!!!");}@Overridepublic void destroy() {System.out.println("---Filter Destruction----");}} 5. Filter deployment
The deployment of Filter is divided into two steps:
1. Register Filter
2. Mapping Filter
5.1. Register Filter
After developing Filter, you need to register in the web.xml file so that you can be called by the web server.
Register Filter example in web.xml file:
<filter><description>FilterDemo filter</description><filter-name>FilterDemo</filter-name><filter-class>me.gacl.web.filter.FilterDemo</filter-class><!--Configure initialization parameters of FilterDemo filter--><init-param><description>Configure initialization parameters of FilterDemo filter</desc ript><param-name>name</param-name><param-value>gacl</param-value></init-param><init-param><description>Configure the initialization parameters of the FilterDemo filter</description><param-name>like</param-name><param-value>java</param-value></init-param></filter>
<description> is used to add description information. The content of this element can be empty and <description> cannot be configured.
<filter-name> is used to specify a name for the filter, and the content of the element cannot be empty.
The <filter-class> element is used to specify the complete qualified class name of the filter.
The <init-param> element is used to specify initialization parameters for the filter, and its child element <param-name> specifies the name of the parameter and <param-value> specifies the value of the parameter. In the filter, the FilterConfig interface object can be used to access the initialization parameters. If the filter does not need to specify initialization parameters, the <init-param> element may not be configured.
5.2. Mapping Filter
After registering Filter in the web.xml file, you must also map Filter in the web.xml file
<!--Mapping filter--><filter-mapping><filter-name>FilterDemo</filter-name><!--"/*" means intercepting all requests--><url-pattern>/*</url-pattern></filter-mapping>
The <filter-mapping> element is used to set the resource that a Filter is responsible for intercepting. A Filter intercepts a resource can be specified in two ways: the servlet name and the request path for resource access.
The <filter-name> child element is used to set the filter's registration name. This value must be the name of the filter declared in the <url-pattern> element. Set the request path intercepted by filter (the URL style associated with the filter)
<servlet-name> Specifies the name of the Servlet intercepted by the filter.
<dispatcher> specifies the way the resource intercepted by the filter is called by the Servlet container. It can be one of REQUEST, INCLUDE, FORWARD and ERROR, and the default REQUEST. Users can set multiple <dispatcher> sub-elements to specify
Filter intercepts various ways of calling resources. as follows:
<filter-mapping><filter-name>testFilter</filter-name><url-pattern>/index.jsp</url-pattern><dispatcher>REQUEST</dispatcher><dispatcher>FORWARD</dispatcher></filter-mapping>
The values that the child element can set and their meanings:
1.REQUEST: When the user directly accesses the page, the web container will call the filter. If the target resource is accessed through the include() or forward() method of the RequestDispatcher, the filter will not be called.
2.INCLUDE: If the target resource is accessed through the include() method of RequestDispatcher, the filter will be called. Other than that, the filter will not be called.
3.FORWARD: If the target resource is accessed through the forward() method of RequestDispatcher, the filter will be called, and the filter will not be called in addition.
4.ERROR: If the target resource is called through the declarative exception handling mechanism, the filter will be called. Other than that, the filter will not be called.