The Java EE 6 Tutorial, Volume I

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

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.

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 10–3, Table 10–4 gives some examples of how the URL will be parsed.

Table 10–3 Aliases

Pattern 

Servlet 

/lawn/*

LawnServlet

/*.jsp

JSPServlet

Table 10–4 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, javax.servlet.http.HttpServletResponse, have fields representing HTTP headers such as the following: