DoFilter method in Servlet

Source: Internet
Author: User

Compile an Implementation Program

The filter API contains three simple interfaces which are neatly nested in the javax. servlet package. The three interfaces are Filter, Filter Chain, and Filter Config. From the programming point of view, the Filter class will implement the Filter interface, and then use the Filter Chain and Filter Config interfaces in this Filter class. A reference of the Filter class is passed to the Filter Chain object, allowing the Filter to pass control to the next resource in the Chain. The Filter Config object is provided to the Filter by the container to allow access to the initialization data of the Filter.

To be consistent with our three-step mode, the Filter must use three methods to fully implement the Filter interface:

Init (): This method is called when the container instantiates a filter. It is mainly designed to prepare the filter for processing. This method accepts an object of the Filter Config type as input.

DoFilter (): Same as servlet which has a service () method, this method calls doPost () or doGet () to process requests, the filter has a single method for processing requests and responses-The doFilter method. This method accepts three input parameters: a Servlet Request, response, and a Filter Chain object.

Destroy (): As you imagine, this method performs any cleanup operations that may need to be performed before automatic garbage collection.

Listing 1 shows a very simple filter that tracks the approximate time taken to satisfy a client's Web requests.
List 1. Implement a filter class

 
 
  1. import javax.servlet.*;  
  2. import java.util.*;  
  3. import java.io.*;  
  4. public class TimeTrackFilter implements Filter {  
  5. private FilterConfig filterConfig = null;  
  6. public void init(FilterConfig filterConfig) throws ServletException {  
  7. this.filterConfig = filterConfig;  
  8. }  
  9. public void destroy() {  
  10. this.filterConfig = null;  
  11. }  
  12. public void doFilter( ServletRequest request, ServletResponse response, 
    FilterChain chain ) throws IOException, ServletException {  
  13. Date startTime, endTime;  
  14. double totalTime;  
  15. startTime = new Date(); // Forward the request to the next resource in 
    the chain chain.doFilter(request, wrapper);  
  16. // -- Process the response -- \\  
  17. // Calculate the difference between the start time and end time  
  18. endTime = new Date();  
  19. totalTime = endTime.getTime() - startTime.getTime();  
  20. totalTimetotalTime = totalTime / 1000; //Convert from milliseconds to 
    seconds StringWriter sw = new StringWriter();  
  21. PrintWriter writer = new PrintWriter(sw);  
  22. writer.println();  
  23. writer.println("===============");  
  24. writer.println("Total elapsed time is: " + totalTime + " seconds." ); 
    writer.println("==============="); // Log the resulting string writer.flush(); 
    filterConfig.getServletContext(). log(sw.getBuffer().toString());  
  25. }  

The lifecycle of this filter is very simple. In any case, let's take a look at it:

Initialization

When the container loads the filter for the first time, the init () method is called. This class contains a reference pointing to the Filter Config object in this method. Our filter does not actually need to do this, because initialization information is not used here, just for demonstration purposes.

Filter

Most of the time consumed by the filter is here. The doFilter method is called by the container and is passed in to reference Servlet Request, Servlet Response, and Filter Chain objects in the Request/Response Chain respectively. The Filter then has the opportunity to process the request, pass the processing task to the next resource in the Chain by calling the doFilter method referenced by the Filter Chain object), and then process the response when the processing control returns the Filter.

Structure Analysis

The container immediately calls the destroy () method before garbage collection to execute any necessary cleanup code.

  1. Servlet Container matching process
  2. How to call Servlet to process requests
  3. Extended Future Response Servlet
  4. Three methods for compiling Servlet
  5. Transactions in Servlet containers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.