9.3. Accessing the Servlet Context from Filters

The ReportFilter of the previous section prints a report on the standard output whenever the designated servlet or JSP page is invoked. A report on the standard output is fine during development—when you run a server on your desktop you typically have a window that displays the standard output. During deployment, however, you are unlikely to have access to this window. So, a natural enhancement is to write the reports into the servlet log file instead of to the standard output.

The servlet API provides two log methods: one that takes a simple String and another that takes a String and a Throwable. These two methods are available from either the GenericServlet or ServletContext classes. Check your server’s documentation for the exact location of the log files that these methods use. The problem is that the doFilter method executes before the servlet or JSP page with which it is associated. So, you don’t have access to the servlet instance and thus can’t call the log methods that are inherited from GenericServlet. Furthermore, the API provides no simple way to access the ServletContext from the doFilter method. The only filter-related class that has a method to access the ServletContext is FilterConfig with its getServletContext method. A FilterConfig object is passed to the init method but is not automatically stored in a location that is available to doFilter.

So, you have to store the FilterConfig yourself. Simply create a field of type FilterConfig, then override init to assign its argument to that field. Since you typically use the FilterConfig object only to access the ServletContext and the filter name, you can store the ServletContext and name in fields as well. Here is a simple example:

public class SomeFilter implements Filter {
  protected FilterConfig config;
						private ServletContext context;
						private String filterName;
						public void init(FilterConfig config)
						throws ServletException {
						this.config = config; // In case it is needed by subclass. 
    context = config.getServletContext();
						filterName = config.getFilterName();
						} 

  // doFilter and destroy methods... 
} 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.109.34