Writing Service Methods - The Java EE 5 Tutorial (original) (raw)

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

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

Writing Service Methods

The service provided by a servlet is implemented in the service method of aGenericServlet, in the do_Method_ methods (where Method can take the value Get, Delete,Options, Post, Put, or Trace) of an HttpServlet object, or in any other protocol-specific methods defined by a class that implements the Servlet interface. In the rest of this chapter, the term service method is used for any method in a servlet class that provides a service to a client.

The general pattern for a service method is to extract information from the request, access external resources, and then populate the response based on that information.

For HTTP servlets, the correct procedure for populating the response is to first retrieve an output stream from the response, then fill in the response headers, and finally write any body content to the output stream. Response headers must always be set before the response has been committed. Any attempt to set or add headers after the response has been committed will be ignored by the web container. The next two sections describe how to get information from requests and generate responses.

Getting Information from Requests

A request contains data passed between a client and the servlet. All requests implement the ServletRequest interface. This interface defines methods for accessing the following information:

For example, in CatalogServlet the identifier of the book that a customer wishes to purchase is included as a parameter to the request. The following code fragment illustrates how to use the getParameter method to extract the identifier:

String bookId = request.getParameter("Add"); if (bookId != null) { Book book = bookDB.getBook(bookId);

You can also retrieve an input stream from the request and manually parse the data. To read character data, use the java.io.BufferedReader object returned by the request’sgetReader method. To read binary data, use the ServletInputStream returned by getInputStream.

HTTP servlets are passed an HTTP request object, HttpServletRequest, which contains the request URL, HTTP headers, query string, and so on.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

If the context path is /catalog and for the aliases listed in Table 4-4,Table 4-5 gives some examples of how the URL will be parsed.

Table 4-4 Aliases

Pattern Servlet
/lawn/* LawnServlet
/*.jsp JSPServlet

Table 4-5 Request Path Elements

Request Path Servlet Path Path Info
/catalog/lawn/index.html /lawn /index.html
/catalog/help/feedback.jsp /help/feedback.jsp null

Query strings are composed of a set of parameters and values. Individual parameters are retrieved from a request by using the getParameter method. There are two ways to generate query strings:

Constructing Responses

A response contains data passed between a server and the client. All responses implement the ServletResponse interface. This interface defines methods that allow you to:

HTTP response objects, HttpServletResponse, have fields representing HTTP headers such as the following:

In Duke’s Bookstore, BookDetailsServlet generates an HTML page that displays information about a book that the servlet retrieves from a database. The servlet first sets response headers: the content type of the response and the buffer size. The servlet buffers the page content because the database access can generate an exception that would cause forwarding to an error page. By buffering the response, the servlet prevents the client from seeing a concatenation of part of a Duke’s Bookstore page with the error page should an error occur. The doGet method then retrieves a PrintWriter from the response.

To fill in the response, the servlet first dispatches the request toBannerServlet, which generates a common banner for all the servlets in the application. This process is discussed in Including Other Resources in the Response. Then the servlet retrieves the book identifier from a request parameter and uses the identifier to retrieve information about the book from the bookstore database. Finally, the servlet generates HTML markup that describes the book information and then commits the response to the client by calling the close method on the PrintWriter.

public class BookDetailsServlet extends HttpServlet { ... public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // set headers before accessing the Writer response.setContentType("text/html"); response.setBufferSize(8192); PrintWriter out = response.getWriter();

    // then write the response
    out.println("<html>" +
        "<head><title>+
        messages.getString("TitleBookDescription")
        +</title></head>");

    // Get the dispatcher; it gets the banner to the user
    RequestDispatcher dispatcher =
        getServletContext().
        getRequestDispatcher("/banner");
    if (dispatcher != null)
        dispatcher.include(request, response);

    // Get the identifier of the book to display
    String bookId = request.getParameter("bookId");
    if (bookId != null) {
        // and the information about the book
        try {
            Book bd =
                bookDB.getBook(bookId);
            ...
            // Print the information obtained
            out.println("<h2>" + bd.getTitle() + "</h2>" +
            ...
        } catch (BookNotFoundException ex) {
            response.resetBuffer();
            throw new ServletException(ex);
        }
    }
    out.println("</body></html>");
    out.close();
}

}

BookDetailsServlet generates a page that looks like Figure 4-2.

Figure 4-2 Book Details

Screen capture of book details. Shows

Previous Contents Next

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