In this article, we will discuss filter ). A filter is an intermediate component that filters between source and target data. The filter can intercept the request and response messages between the client and the resource, and filter these messages.
When a Web Container receives a request for a resource, it first determines whether a filter is connected to the resource. If yes, the container will send the request to the filter for processing. In the filter, you can change the request content or reset the request header information. When the target resource responds to the request, the container also forwards the response to the filter first. In the filter, you can convert the response content and then send the response to the client. Filters are transparent to clients and target resources.
You can deploy multiple filters in a web application to form a filter chain. Each filter in the filter chain is responsible for specific operations and tasks. The main application of the filter is as follows:
Unified authentication of user requests
Record and review user requests
Filter and convert user data
Convert image format
Compresses the response content to reduce the transmission volume.
Encrypt requests and responses
Trigger Resource Access Events
Filter API
The interfaces and classes related to filter development are included in the javax. servlet and javax. servlet. Http packages. They mainly include the following interfaces and classes.
Javax. servlet. filter // interface javax. servlet. filterconfig // interface javax. servlet. filterchain // interface javax. servlet. servletrequestwrapper // class javax. servlet. servletresponsewrapper // class javax. servlet. HTTP. httpservletrequestwrapper // class javax. servlet. HTTP. httpservletresponsewrapper // class
First, we will introduce three main interfaces.
Filter Interface
Filter interfaces must be implemented for the development of filters. The filter interface defines three methods.
1) Init (), the Web Container calls this method to initialize the filter. When the container calls this method, it passes the filterconfig object to the filter. The usage of filterconfig is similar to that of servletconfig. Filterconfig can be used to obtain the servletcontext object and the initialization parameters of the filter configured in the deployment description file.
2) dofilter. This method is similar to the servlet Service () method. When the client requests the target resource, the container will call the dofilter () method of the filter managed by the target resource. In this method, you can process the request and response. After processing, you can also call the chain. dofilter (request, response) transmits the request to the next filter. It can also be directly sent back to the client.
3) destroy (). The Web Container calls this method to indicate that the lifecycle of the filter is over. In this method, resources used by the filter can be released.
Unlike servlet development, the filter interface does not have a corresponding class for inheritance. To develop a filter, you can only implement the filter interface.
Filterconfig Interface
This interface is implemented by containers. It is similar to the servlet servletconfig interface and is used to transmit information to the filter during initialization. In this interface, four methods are defined.
1) getfiltername () to get the name of the specified filter in the deployment description file
2) getinitparameter (string name) to get the value of the initialization parameter specified in the deployment description file with name
3) getinitparameternames () returns an enumeration set of the names of all initialization parameters of the filter. If no initialization parameter exists, a null value is returned.
4) getservletcontext () returns the reference of the servlet context object.
Filterchain Interface
This interface is implemented by the container. The container passes its instance as a parameter to the dofilter () method of the filter object. The filter object uses the filterchain object to call the next filter in the filter chain. If the filter is the last filter of the filter chain, the target resource is called. It has only one method:
Dofilter (request, response). Calling this method will call the next filter in the filter chain. If the filter used to call this method is the last one in the chain, the target resource will be called.
Filter deployment
After implementing a filter, you must configure the filter in the deployment description file. The configuration is completed through <filter> and <filter-mapping>. An example of a configuration description file is as follows:
<?xml version='1.0' encoding='utf-8'?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"><filter><filter-name>TestFilter</filter-name><filter-class>com.shan.filter.TestFilter</filter-class><init-param><param-name>word</param-name><param-value>/WEB-INF/word.txt</param-value></init-param></filter><filter-mapping><filter-name>TestFilter</filter-name><url-pattern>/test.jsp</url-pattern><servlet-name>servlet1</servlet-name><servlet-name>*</servlet-name><dispatcher>REQUEST</dispatcher></filter-mapping></web-app>
The <URL-pattern> element specifies the URL style associated with the filter, and <servlet-Name> specifies the servlet corresponding to the filter. If <filter-mapping> is set to *, it indicates any servlet. The <filter-mapping> element can also contain up to four <dispatcher> elements. This element specifies the request method corresponding to the filter, which can be one of request, include, forward, and error. The default value is request.
Now let's look at a filter demo program. The Project Creation steps are exactly the same as those before and will not be repeated here.
Write filter class
package com.shan.filter;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class TestFilter implements Filter {public void init(FilterConfig config) throws ServletException {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {response.setContentType("text/html;charset=gb2312");PrintWriter out = response.getWriter();out.println("Before doFilter()");chain.doFilter(request,response);out.println("After doFilter()");out.close();}public void destroy() {}}
Compile the test page
<%@ page contentType="text/html;charset=gb2312" %>This is a test page..
Compile and deploy Filters
<?xml version='1.0' encoding='utf-8'?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"><filter><filter-name>TestFilter</filter-name><filter-class>com.shan.filter.TestFilter</filter-class></filter><filter-mapping><filter-name>TestFilter</filter-name><url-pattern>/test.jsp</url-pattern></filter-mapping></web-app>
Switch to the project directory in the DOS environment and run the following statement to compile the testfilter class:
javac -classpath D:\apache-tomcat-7.0.33\lib\servlet-api.jar;classes -d classes src\com\shan\filter\TestFilter.java
Configuration program
Create a new testfilter folder under the D: \ apache-Tomcat-7.0.33 \ webapps folder, create a WEB-INF directory under the testfilter folder, copy the compiled classes folder to the WEB-INF directory. Copy the created test. jsp file to the testfilter folder.
Running result
Enter localhost: 8080/testfilter/test. jsp in the browser URL bar. The result is as follows:
We can see that before outputting this is a test, we first run the dofilter output statement, output before dofilter (), and then call chain. dofilter (request, response) transmits the request to the next filter. Because no other filter exists after this, it is passed to the target resource and the output of this is a test, the dofilter statement is called again in the response and the output is after dofilter ().
Filter request and Response Data
In the message board program, if the user inputs illegal strings, these strings should be blocked. However, the httpservletrequset class does not provide the setxxx () method for modifying request information, and the httpservletresponse class does not provide the method for obtaining response data. Therefore, although the filter can intercept request and response objects, however, these two objects cannot be directly used to replace their data. However, the servlet specification defines four packaging classes: servletrequsetwrapper, servletresponsewrapper, httpservletrequsetwrapper, and httpservletreponsewrapper. These four packages implement the request or response interfaces respectively. They receive real request or response objects in the constructor, and then use the methods of this object to complete the methods they need to implement.
With the packaging class, to modify the request or response information, you only need to write a subclass of the packaging class, and then Gu Fei wants to modify the method. For example, if we want to add a query string for all requests, we can write a subclass of the httpservletrequestwrapper class, rewrite the getquerystring () method, and then in the dofilter () method of the filter, construct the object of this subclass and pass it as a parameter to the chain. dofilter () method.
Filter for compressing the response content
The website access speed is determined by many factors, including server performance, network bandwidth, web program response speed, and network transmission speed of servers and clients. From the software point of view, we need to increase the speed of Website access, that is, to increase the speed of Web application execution as much as possible, which can be achieved through code optimization. To further improve the Webpage Browsing speed, you can compress the response content to save network bandwidth and increase the access speed.
Currently, mainstream browsers support compressed webpage content, including gzip and deflate compression methods. The communication process between browsers and web servers for compressing web pages is as follows:
1) if the browser can accept the compressed webpage content, it will send the accept-encoding header in the request and set the content to gzip.
2) The web server reads the value of the accept-encoding request header to determine whether the browser accepts compression. If yes, the response content of the target page is compressed and then sent to the client, set the content-encoding object header.
3) after the browser receives the response content, decompress the response content according to the value in content-encoding and display it.
We can use a filter to compress the response content of the target page. This process is similar to a filter to filter the request and response content. The actual principle is to replace the original response object with the packaging class object, and use java.util.zip. gzipoutputstream as the output stream object of the response content.
Reprinted please indicate the source: http://blog.csdn.net/iAm333