Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

What Is a Servlet?

The Example Servlets

Troubleshooting Duke's Bookstore Database Problems

Servlet Life Cycle

Handling Servlet Life-Cycle Events

Defining the Listener Class

Specifying Event Listener Classes

Handling Servlet Errors

Sharing Information

Using Scope Objects

Controlling Concurrent Access to Shared Resources

Accessing Databases

Initializing a Servlet

Writing Service Methods

Getting Information from Requests

Constructing Responses

Filtering Requests and Responses

Programming Filters

Programming Customized Requests and Responses

Specifying Filter Mappings

Invoking Other Web Resources

Including Other Resources in the Response

Transferring Control to Another Web Component

Accessing the Web Context

Maintaining Client State

Accessing a Session

Associating Objects with a Session

Notifying Objects That Are Associated with a Session

Session Management

Session Tracking

Finalizing a Servlet

Tracking Service Requests

Notifying Methods to Shut Down

Creating Polite Long-Running Methods

Further Information about Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

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

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

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

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Filtering Requests and Responses

Afilter 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:

  • Query the request and act accordingly.

  • Block the request-and-response pair from passing any further.

  • Modify the request headers and data. You do this by providing a customized version of the request.

  • Modify the response headers and data. You do this by providing a customized version of the response.

  • Interact with external resources.

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 the filter

  • Programming customized requests and responses

  • Specifying the filter chain for each web resource

Programming Filters

The 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:

  • Examine the request headers.

  • Customize the request object if the filter wishes to modify request headers or data.

  • Customize the response object if the filter wishes to modify response headers or data.

  • Invoke the next entity in the filter chain. If the current filter is the last filter in the chain that ends with the target web component or static resource, the next entity is the resource at the end of the chain; otherwise, it is the next filter that was configured in the WAR. The filter invokes the next entity by calling thedoFilter method on the chain object (passing in the request and response it was called with, or the wrapped versions it may have created). Alternatively, it can choose to block the request by not making the call to invoke the next entity. In the latter case, the filter is responsible for filling out the response.

  • Examine response headers after it has invoked the next filter in the chain.

  • Throw an exception to indicate an error in processing.

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 Responses

There 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

Screen capture of Duke's Bookstore with

Specifying Filter Mappings

A 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:

  1. Expand the application’s project node in the Project pane.

  2. Expand the Web Pages and WEB-INF nodes under the project node.

  3. Double-clickweb.xml.

  4. Click Filters at the top of the editor pane.

  5. Expand the Servlet Filters node in the editor pane.

  6. Click Add Filter Element to map the filter to a web resource by name or by URL pattern.

  7. In the Add Servlet Filter dialog, enter the name of the filter in the Filter Name field.

  8. Click Browse to locate the servlet class to which the filter applies. You can include wildcard characters so that you can apply the filter to more than one servlet.

  9. Click OK.

To constrain how the filter is applied to requests, do the following:

  1. Expand the Filter Mappings node in the Filters tab of the editor pane.

  2. Select the filter from the list of filters.

  3. Click Add.

  4. In the Add Filter Mapping dialog, select one of the following dispatcher types:

    • REQUEST: Only when the request comes directly from the client

    • FORWARD: Only when the request has been forwarded to a component (seeTransferring Control to Another Web Component)

    • INCLUDE: Only when the request is being processed by a component that has been included (seeIncluding Other Resources in the Response)

    • ERROR: Only when the request is being processed with the error page mechanism (seeHandling Servlet Errors)

      You can direct the filter to be applied to any combination of the preceding situations by selecting multiple dispatcher types. If no types are specified, the default option isREQUEST.

You can declare, map, and constrain the filter by editing the XMLin the web application deployment descriptor directly by following these steps:

  1. While in theweb.xml editor pane in NetBeans IDE, click XML at the top of the editor pane.

  2. Declare the filter by adding afilter element right after thedisplay-name element. Thefilter element creates a name for the filter and declares the filter’s implementation class and initialization parameters.

  3. Map the filter to a web resource by name or by URL pattern using thefilter-mapping element:

    1. Include afilter-name element that specifies the name of the filter as defined by thefilter element.

    2. Include aservlet-name element that specifies to which servlet the filter applies. Theservlet-name element can include wildcard characters so that you can apply the filter to more than one servlet.

  4. Constrain how the filter will be applied to requests by specifying one of the enumerated dispatcher options (described in step 4 of the preceding set of steps) with thedispatcher element and adding thedispatcher element to thefilter-mapping element.

    You can direct the filter to be applied to any combination of the preceding situations by including multipledispatcher elements. If no elements are specified, the default option isREQUEST.

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

Filter

Class

Servlet

HitCounterFilter

filters.HitCounterFilter

BookStoreServlet

OrderFilter

filters.OrderFilter

ReceiptServlet

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

Diagram of filter-to-servlet mapping with filters F1-F3 and servlets S1-S3. F1 filters S1-S3, then F2 filters S2, then F3 filters S1 and S2.

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.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp