Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 9. Servlet and JSP Filters > Example: An Access Time Filter

9.6. Example: An Access Time Filter

The LogFilter of Section 9.4 prints an entry in the log file every time the associated servlet or JSP page is accessed. Suppose you want to modify it so that it only notes accesses that occur at unusual times. Since “unusual” is situation dependent, the servlet should provide default values for the abnormal time ranges and let deployers override these values by supplying initialization parameters. To implement this functionality, the filter has the following capabilities.

  1. A class that implements the Filter interface. This class is called LateAccessFilter and is shown in Listing 9.9. The init method of this class reads the startTime and endTime initialization parameters. It attempts to parse these values as type int, using default values if the parameters are null or not formatted as integers. It then stores the start and end times, the FilterConfig, the ServletContext, and the filter name in fields of the filter. Finally, LateAccessFilter provides an empty body for the destroy method.

  2. Filtering behavior in the doFilter method. This method looks up the current time, sees if it is within the range given by the start and end times, and prints a log entry if so.

  3. A call to the doFilter method of the FilterChain. After printing the report, the filter calls the doFilter method of the FilterChain to invoke the next filter in the chain (or the servlet or JSP page if there are no more filters).

  4. Registration with the Web application home page; definition of initialization parameters. First, the filter element associates the name LateAccessFilter with the class moreservlets.filters.LateAccessFilter. The filter element also includes two init-param subelements: one that defines the startTime parameter and another that defines endTime. Since the people that will be accessing the filtersRus home page are programmers, an abnormal range is considered to be between 2:00 a.m. and 10:00 a.m. Finally, the filter-mapping element uses a url-pattern of /index.jsp to associate the filter with the Web application home page. See Listing 9.10.

  5. Disablement of the invoker servlet. This operation is shown in Section 9.2 and is not repeated here.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint