Filter of Java Web

Filter is called filter or interceptor. Its basic function is to intercept the process of calling servlet, and realize some special functions before and after servlet response and processing. In fact, the filter is an implementation of javax servlet. Class of filter interface, in javax servlet. Three methods are defined in the filter interface:

1. Implement the first filter program

Index. The java file is as follows:

MyFilter. The java file is as follows:

web. Add the following code to the XML configuration file:

The test results are as follows:

2. Filter chain

The example of filter chain is as follows:

The test procedure is as follows, index Java file and myfilter The java file reference implements the code in the first filter program, myfilter2 Java files and web The XML configuration file is as follows:

MyFilter2. The java file is as follows:

web. Add the following code to the XML configuration file:

The test results are as follows:

Note: what is the calling order between filters? This is different from them on the web The sequence of declarations in XML is related, for example, according to the above web XML configuration, the calling order of filter is:

Request - > myfilter - > myfilter2 - > index (servlet)

Response < - myfilter < - myfilter2 < - index (servlet)

3. Filter lifecycle

The web server is responsible for the creation and destruction of filters. When the web application starts, the web server will create an instance object of filter and call its init method to complete the initialization function of the object, so as to prepare for interception of subsequent user requests. The filter object will be created only once and the init method will be executed only once. The filterconfig object representing the current filter configuration information can be obtained through the parameters of the init method. The filterconfig interface encapsulates the filter program in the web XML, and provides some methods to obtain these configuration information, as shown below:

MyFilter. The java file is as follows

MyFilter. Java corresponding web XML configuration items are as follows:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>