background image

The doFilter() Method

<< Programming Filters | Programming Customized Requests and Responses >>
<< Programming Filters | Programming Customized Requests and Responses >>

The doFilter() Method

The Duke's Bookstore application uses the filters HitCounterFilter and OrderFilter, located
at
tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/filters/,
to increment and log the value of counters when the entry and receipt servlets are accessed.
In the doFilter method, both filters retrieve the servlet context from the filter configuration
object so that they can access the counters stored as context attributes. After the filters have
completed application-specific processing, they invoke doFilter on the filter chain object
passed into the original doFilter method. The elided code is discussed in the next section.
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (filterConfig == null)
return;
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
Counter counter = (Counter)filterConfig.
getServletContext().
getAttribute(
"hitCounter");
writer.println();
writer.println(
"===============");
writer.println(
"The number of hits is: " +
counter.incCounter());
writer.println(
"===============");
// Log the resulting string
writer.flush();
System.out.println(sw.getBuffer().toString());
...
chain.doFilter(request, wrapper);
...
}
}
Filtering Requests and Responses
The Java EE 5 Tutorial · September 2007
116