The Java EE 5 Tutorial

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