background image

Writing Service Methods

<< Initializing a Servlet | Context Path and Servlet Path >>
<< Initializing a Servlet | Context Path and Servlet Path >>

Writing Service Methods

Writing Service Methods
The service provided by a servlet is implemented in the service method of a GenericServlet,
in the doMethod 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:
Parameters, which are typically used to convey information between clients and servlets
Object-valued attributes, which are typically used to pass information between the servlet
container and a servlet or between collaborating servlets
Information about the protocol used to communicate the request and about the client and
server involved in the request
Information relevant to localization
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
BufferedReader
object returned by the request's getReader 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.
Writing Service Methods
The Java EE 5 Tutorial · September 2007
110