2. Using the Tutorial Examples 3. Getting Started with Web Applications Troubleshooting Duke's Bookstore Database Problems Handling Servlet Life-Cycle Events Specifying Event Listener Classes Controlling Concurrent Access to Shared Resources Getting Information from Requests Including Other Resources in the Response Transferring Control to Another Web Component Associating Objects with a Session Notifying Objects That Are Associated with a Session Notifying Methods to Shut Down Creating Polite Long-Running Methods Further Information about Java Servlet Technology 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | Filtering Requests and ResponsesAfilter is an object that can transform the header and content (orboth) of a request or response. Filters differ from web components in thatfilters usually do not themselves create a response. Instead, a filter provides functionality thatcan be “attached” to any kind of web resource. Consequently, a filter shouldnot have any dependencies on a web resource for which it is actingas a filter; this way it can be composed with more thanone type of web resource. The main tasks that a filter can perform are as follows:
Applications of filters include authentication, logging, image conversion, data compression, encryption, tokenizing streams,XML transformations, and so on. You can configure a web resource to be filtered by a chainof zero, one, or more filters in a specific order. This chain isspecified when the web application containing the component is deployed and is instantiatedwhen a web container loads the component. In summary, the tasks involved in using filters are
Programming FiltersThe filtering API is defined by theFilter,FilterChain, andFilterConfig interfaces in thejavax.servlet package. You define a filter by implementing theFilter interface. The most important method in this interface isdoFilter, which is passed request,response, and filter chain objects. This method can perform the following actions:
In addition todoFilter, you must implement theinit anddestroy methods. Theinit method is called by the container when the filter is instantiated. Ifyou wish to pass initialization parameters to the filter, you retrieve them fromtheFilterConfig object passed toinit. The Duke’s Bookstore application uses the filtersHitCounterFilter andOrderFilter, located attut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/filters/, to increment and log the value of counters when the entryand receipt servlets are accessed. In thedoFilter method, both filters retrieve the servlet context from the filterconfiguration object so that they can access the counters stored as context attributes.After the filters have completed application-specific processing, they invokedoFilter on the filter chainobject passed into the originaldoFilter method. The elided code is discussed inthe 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); ... }}Programming Customized Requests and ResponsesThere are many ways for a filter to modify a request orresponse. For example, a filter can add an attribute to the request orcan insert data in the response. In the Duke’s Bookstore example,HitCounterFilter insertsthe value of the counter into the response. A filter that modifies a response must usually capture the response before itis returned to the client. To do this, you pass a stand-instream to the servlet that generates the response. The stand-in stream prevents the servletfrom closing the original response stream when it completes and allows the filterto modify the servlet’s response. To pass this stand-in stream to the servlet, the filter creates a responsewrapper that overrides thegetWriter orgetOutputStream method to return this stand-instream. The wrapper is passed to thedoFilter method of the filter chain.Wrapper methods default to calling through to the wrapped request or response object.This approach follows the well-known Wrapper or Decorator pattern described inDesign Patterns, Elements of Reusable Object-Oriented Software, by ErichGamma et al. (Addison-Wesley, 1995). The following sections describe how the hit counterfilter described earlier and other types of filters use wrappers. To override request methods, you wrap the request in an object that extendsServletRequestWrapper orHttpServletRequestWrapper. To override response methods, you wrap the response in anobject that extendsServletResponseWrapper orHttpServletResponseWrapper. HitCounterFilter wraps the response in atut-install/javaeetutorial5/examples/web/bookstore1/src/java/com/sun/bookstore1/filters/CharResponseWrapper. The wrapped response is passedto the next object in the filter chain, which isBookStoreServlet. ThenBookStoreServletwrites its response into the stream created byCharResponseWrapper. Whenchain.doFilter returns,HitCounterFilter retrieves the servlet’s response fromPrintWriter and writes it to a buffer.The filter inserts the value of the counter into the buffer, resets thecontent length header of the response, and then writes the contents of thebuffer to the response stream. PrintWriter out = response.getWriter();CharResponseWrapper wrapper = new CharResponseWrapper( (HttpServletResponse)response);chain.doFilter(request, wrapper);CharArrayWriter caw = new CharArrayWriter();caw.write(wrapper.toString().substring(0, wrapper.toString().indexOf("</body>")-1));caw.write("<p>\n<center>" + messages.getString("Visitor") + "<font color=’red’>" + counter.getCounter() + "</font></center>");caw.write("\n</body></html>");response.setContentLength(caw.toString().getBytes().length);out.write(caw.toString());out.close();public class CharResponseWrapper extends HttpServletResponseWrapper { private CharArrayWriter output; public String toString() { return output.toString(); } public CharResponseWrapper(HttpServletResponse response){ super(response); output = new CharArrayWriter(); } public PrintWriter getWriter(){ return new PrintWriter(output); }}Figure 4-3 shows the entry page for Duke’s Bookstore with the hit counter. Figure 4-3 Duke’s Bookstore with Hit Counter ![]() Specifying Filter MappingsA web container uses filter mappings to decide how to apply filters toweb resources. A filter mapping matches a filter to a web component byname, or to web resources by URL pattern. The filters are invoked inthe order in which filter mappings appear in the filter mapping list ofa WAR. You specify a filter mapping list for a WAR in itsdeployment descriptor, either with NetBeans IDE or by coding the list by handwith XML. To declare the filter and map it to a web resource usingNetBeans IDE, do the following:
To constrain how the filter is applied to requests, do the following:
You can declare, map, and constrain the filter by editing the XMLin the web application deployment descriptor directly by following these steps:
If you want to log every request to a web application, youmap the hit counter filter to the URL pattern/*.Table 4-6 summarizes thefilter definition and mapping list for the Duke’s Bookstore application. The filters arematched by servlet name, and each filter chain contains only one filter. Table 4-6 Duke’s Bookstore Filter Definition and Mapping List
You can map a filter to one or more web resources and youcan map more than one filter to a web resource. This is illustratedinFigure 4-4, where filter F1 is mapped to servlets S1, S2, and S3,filter F2 is mapped to servlet S2, and filter F3 is mapped toservlets S1 and S2. Figure 4-4 Filter-to-Servlet Mapping ![]() Recall that a filter chain is one of the objects passed to thedoFilter method of a filter. This chain is formed indirectly by means offilter mappings. The order of the filters in the chain is the sameas the order in which filter mappings appear in the web application deploymentdescriptor. When a filter is mapped to servlet S1, the web container invokes thedoFilter method of F1. ThedoFilter method of each filter in S1’sfilter chain is invoked by the preceding filter in the chain by meansof thechain.doFilter method. Because S1’s filter chain contains filters F1 and F3,F1’s call tochain.doFilter invokes thedoFilter method of filter F3. When F3’sdoFiltermethod completes, control returns to F1’sdoFilter method. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |