10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Filtering Requests and Responses<br />

116<br />

<strong>The</strong> Duke’s Bookstore application uses the filters HitCounterFilter and OrderFilter, located<br />

at<br />

tut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/filters/,<br />

to increment and log the value of counters when the entry and receipt servlets are accessed.<br />

In the doFilter method, both filters retrieve the servlet context from the filter configuration<br />

object so that they can access the counters stored as context attributes. After the filters have<br />

completed application-specific processing, they invoke doFilter on the filter chain object<br />

passed into the original doFilter method. <strong>The</strong> elided code is discussed in the next section.<br />

public final class HitCounterFilter implements Filter {<br />

private FilterConfig filterConfig = null;<br />

}<br />

public void init(FilterConfig filterConfig)<br />

throws ServletException {<br />

this.filterConfig = filterConfig;<br />

}<br />

public void destroy() {<br />

this.filterConfig = null;<br />

}<br />

public void doFilter(ServletRequest request,<br />

ServletResponse response, FilterChain chain)<br />

throws IOException, ServletException {<br />

if (filterConfig == null)<br />

return;<br />

StringWriter sw = new StringWriter();<br />

PrintWriter writer = new PrintWriter(sw);<br />

Counter counter = (Counter)filterConfig.<br />

getServletContext().<br />

getAttribute("hitCounter");<br />

writer.println();<br />

writer.println("===============");<br />

writer.println("<strong>The</strong> number of hits is: " +<br />

counter.incCounter());<br />

writer.println("===============");<br />

// Log the resulting string<br />

writer.flush();<br />

System.out.println(sw.getBuffer().toString());<br />

...<br />

chain.doFilter(request, wrapper);<br />

...<br />

}<br />

<strong>The</strong> <strong>Java</strong> <strong>EE</strong> 5<strong>Tutorial</strong> • June 2010

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!