426 CHAPTER 10 INTRODUCTION TO FILTERING chaining order is the order of declaration within the web.xml file, as expected. Creating an AuditFilter Both SimpleFilter and SimpleFilter2just write to the log, so now let s create the first filter that delivers a little extra. It will audit resource access by logging the time of access, the IP address of the client, the resource being accessed, and the time spent fulfilling the request. For brevity, we ll show the code for only the doFilter() method from the AuditFilter class here (see Listing 10-6); the rest of the code is no different from the previous filters. This filter takes advantage of the request object to obtain the required information. It also times the access to the resource by storing the system time before the FilterChain.doFilter() call. After the resource processing, it creates the log entry containing all the information. Listing 10-6. AuditFilter.java (doFilter() Method) public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { long startTime = System.currentTimeMillis(); String remoteAddress = request.getRemoteAddr(); String remoteHost = request.getRemoteHost(); HttpServletRequest myReq = (HttpServletRequest) request; String reqURI = myReq.getRequestURI(); chain.doFilter(request, response); filterConfig.getServletContext().log( “User at IP ” + remoteAddress + “(” + remoteHost + “) accessed resource ” + reqURI + ” and used ” + (System.currentTimeMillis() - startTime) + ” ms”); } Note the ease with which this summary information is maintained and written, using local variables in the doFilter()method itself. Thanks to the nested-call nature of filters, maintaining states across the two processing windows before and after resource access is simple. Edit the web.xml file by adding the following declarations to the file and changing the entries for SimpleFilter and SimpleFilter2from the previous example: Audit Filter com.apress.projsp.filters.AuditFilter Audit Filter /* Simple Filter /index.jsp
In case you need affordable webhost to host your website, our recommendation is ecommerce web host services.
This entry was posted
on Sunday, February 10th, 2008 at 9:57 am and is filed under Jsp.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.