Deeply analyze the principle and application of java servlet filter
1. Servlet filter 1.1 what is a filter? A filter is a program that runs on the server before its associated servlet or JSP page. Filters can be attached to one or more servlets or JSP pages and can check the request information entering these resources. After that, The filter can make the following choices: ① call resources in a conventional way (that is, call the servlet or JSP page). ② use the modified request information to call the resource. ③ call the resource, but modify it before sending the response to the client. ④ block the resource call, instead go to other resources, return a specific status code or generate replacement output. 1.2 the basic principle of servlet filter is that servlet is used as a filter It can process customer requests. After processing, it will be handed over to the next filter for processing. In this way, the customer's requests will be processed one by one in the filter chain until the request is sent to the target. For example, there is a web page to submit "modified registration information" in a website. When the user fills in the modified information and submits it, the server needs to do two things: judge whether the client's session is valid; Uniformly code the submitted data. These two tasks can be handled in a filter chain composed of two filters. When the filter is processed successfully, send the submitted data to the final target; If the filter processing is unsuccessful, the view will be sent to the specified error page.
2. Servlet filter development steps the steps of developing servlet filter are as follows: ① write the servlet class that implements the filter interface. ② On the web Configure filter in XML. To develop a filter, you need to implement the filter interface. The filter interface defines the following methods: ① destroy() is called by the web container to initialize the filter. ② init (filterconfig filterconfig) is called by the web container to initialize the filter. ③ dofilter (ServletRequest request, servletresponse response, filterchain chain) specific filter processing code.
3. A filter framework instance simplefilter1 java
SimpleFilter2. java
web. xml
Open any page in the web container and output the results: (note the request / response order executed by the filter)
4. Report filter let's try a simple filter. As long as the relevant servlet or JSP page is called, it will print a message to the standard output. To achieve this, the filtering behavior is performed in the dofilter method. Whenever the servlet or JSP page associated with this filter is called, the dofilter method generates a printout listing the requesting host and the URL of the call. Because the getrequesturl method is located in HttpServletRequest instead of ServletRequest, the ServletRequest object is constructed as HttpServletRequest type. Let's change simplefilter1 in Chapter 3 java。 SimpleFilter1. java
web. XML settings remain unchanged, the same as Chapter 3. Test: enter [url] http://localhost:8080/Test4Jsp/login.jsp [/ url] result:
5. Under the filter during access (use servlet initialization parameters in the filter), use init to set a normal access time range and record those accesses that are not in this time period. Let's change simplefilter2.java in Chapter 3.
web. The XML settings remain unchanged. Tomcat log processing is introduced here. config. getServletContext(). Log ("log message") will write the log information into the < catalina_home > / logs folder. The file name should be in the form of localhost_log.2007-03-04.txt (one is generated every day according to the date and can be seen the next day). To get such a log file, there should be: < logger classname = "org. Apache. Catalina. Logger. FileLogger" prefix = "catalina_log." suffix=".txt" timestamp="true"/>
6. Disable site filter if you want to interrupt the subsequent filtering process when your filter detects abnormal exceptions:
The following example is a forbidden site filter. If you don't want some sites to visit your website, you can XML lists its sites in param value, and then applies the above principle to jump out of the conventional filtering and give the pages that are forbidden to visit. BannedAccessFilter. java
web. xml
Test:
result:
7. Replacing filters 7.1 modifying response filters can prevent access to resources or activation of them. But if the filter wants to change the response generated by the resource. What shall I do? There seems to be no way to access the response generated by a resource. Second parameter of dofilter (servletresponse) provides the filter with a way to send new output to the client, but does not provide the filter with a way to access the servlet or JSP page output. Why is this? Because when the dofilter method is called for the first time, the servlet or JSP page has not even been executed. Once the dofilter method in the filterchain object is called, modify the response It seems too late that the data has been sent to the client. However, there is a way to modify the response object of the dofilter method passed to the filterchain object. In general, build versions that cache all output generated by servlets or JSP pages. Servlet API version 2.3 provides a useful resource for this, that is, the httpservletresponsewrapper class. The use of this class includes the following five steps: 1) create a response wrapper. Extend javax servlet. http. HttpServletResponseWrapper。 2) Provides a printwriter that caches output. Overload the getwriter method, return a printwriter that holds everything sent to it, and store the results in a field that can be accessed later. 3) Pass this wrapper to dofilter. This call is legal because httpservletresponsewrapper implements httpservletresponse. 4) Extract and modify the output. After calling the dofilter method of filterchain, the output of the original resource can be obtained by using the mechanism provided in step 2. As long as it suits your application, you can modify or replace it. 5) Send the modified output to the client. Because the original resource no longer sends output to the client (these outputs have been stored in your response wrapper), so you must send these outputs. In this way, your filter needs to obtain printwriter or OutputStream from the original response object and pass the modified output to the stream. 7.2 a reusable response wrapper. The following example program gives a wrapper that can be used for the output of resources you want the filter to modify In most applications. The chararraywrapper class overloads the getwriter method to return a printwriter that accumulates everything in a large character array. Developers can use the tochararray (original char []) or toString (a string derived from char []) method to get this result. Chararraywrapper.java
7.3 replacement filter here is a common application of chararraywrapper given in the previous section: changing a multiple occurrence target string to a replacement string filter. 7.3. 1. Replace filter Java gives a filter, which wraps the response in the chararrarywrapper, passes the wrapper to the dofilter method of the filterchain object, extracts a string value that gives the output of all resources, replaces all occurrences of a target string with a replacement string, and sends the modified result to the client. There are two things to note about this filter. First, it is an abstract class. To use it, you must create a subclass that provides an implementation of the gettargetstring and getreplacementstring methods. An example of this processing is given in the next section. Second, it uses a smaller utility class (see filterutils. Java) for actual string replacement. You can use the new regular expression package instead of the low-level and cumbersome methods in string and stringtokenizer. Replacefilter.java
FilterUtils. java
web. xml
Test result: before filtering
After filtration
8. The compression filter has several latest browsers that can process the compressed content, automatically unpack the compressed file with gzip as the content encoding response header value, and then process the results like the original document. Sending such compressed content can save a lot of time, because the time required to compress the document on the server and then unpack the document on the client is insignificant compared with the time required to download the file. Program longservlet Java provides a servlet with long and repeated plain text output, which is a mature servlet for compression. If you use gzip, it can compress the output to 1 / 300! When the browser supports this compression capability, the compression filter can use the chararraywrapper described in Chapter 7 to compress the content. To complete this task, the following contents are required: 1) the class that implements the filter interface. This class is called compressionfilter. The init method stores the filterconfig object in a field to prevent subclasses from accessing the servlet environment or filter name. The destruction method body is empty. 2) Wrapped response object. The dofilter method wraps the servletresponse object in a chararraywrapper and passes the wrapper to the dofilter method of the filterchain object. After this call is complete, all other filters and final resources are executed and the output is in the wrapper. In this way, the original dofilter extracts a character array representing the output of all resources. If the client indicates that it supports compression (that is, gzip is used as a value of the accept encoding header), the filter attaches a gzipoutputstream to the bytearrayoutputstream, copies the character array to the stream, and sets the content encoding response header to gzip. If the client does not support gzip, the unmodified character array is copied to the bytearrayoutputstream. Finally, dofilter (possibly compressed) write to the OutputStream related to the original response and send the results to the client. 3) register the longservlet. Compressionfilter.java
web. xml