The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Servlets
Lesson: Interacting with Clients

## Requests and Responses

> Methods in the `HttpServlet` class that handle client requests take two arguments:

> 1. An `HttpServletRequest` object, which encapsulates the data from the client
> 2. An `HttpServletResponse` object, which encapsulates the response to the client

### HttpServletRequest Objects

An `HttpServletRequest` object provides access to HTTP header data, such as any cookies found in the request and the HTTP method with which the request was made. The `HttpServletRequest` object also allows you to obtain the arguments that the client sent as part of the request.

To access client data:

- The `getParameter` method returns the value of a named parameter. If your parameter could have more than one value, use `getParameterValues` instead. The `getParameterValues` method returns an array of values for the named parameter. (The method `getParameterNames` provides the names of the parameters.)
- For HTTP GET requests, the `getQueryString` method returns a `String` of raw data from the client. You must parse this data yourself to obtain the parameters and values.
- For HTTP POST, PUT, and DELETE requests,
  - If you expect text data, the `getReader` method returns a `BufferedReader` for you to use to read the raw data.
  - If you expect binary data, the `getInputStream` method returns a `ServletInputStream` for you to use to read the raw data

> Note: Use either a `getParameter[Values]` method or one of the methods that allow you to parse the data yourself. They can not be used together in a single request.

### HttpServletResponse Objects

An `HttpServletResponse` object provides two ways of returning data to the user:

- The `getWriter` method returns a `Writer`
- The `getOutputStream` method returns a `ServletOutputStream`

Use the `getWriter` method to return text data to the user, and the `getOutputStream` method for binary data.

Closing the `Writer` or `ServletOutputStream` after you send the response allows the server to know when the response is complete.

### HTTP Header Data

You must set HTTP header data before you access the `Writer` or `OutputStream`. The `HttpServletResponse` class provides methods to access the header data. For example, the `setContentType` method sets the content type. (This header is often the only one manually set.)

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form