Interacting with Clients |
Methods in the
HttpServlet
class that handle client requests take two arguments:
- An
HttpServletRequest
object, which encapsulates the data from the client
- 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. TheHttpServletRequest
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, usegetParameterValues
instead. ThegetParameterValues
method returns an array of values for the named parameter. (The methodgetParameterNames
provides the names of the parameters.)
- For HTTP GET requests, the
getQueryString
method returns aString
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 aBufferedReader
for you to use to read the raw data.
- If you expect binary data, the
getInputStream
method returns aServletInputStream
for you to use to read the raw data
Note: Useeither agetParameter[Values]
methodor 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 aWriter
- The
getOutputStream
method returns aServletOutputStream
Use the
getWriter
method to return text data to the user, and thegetOutputStream
method for binary data.Closing the
Writer
orServletOutputStream
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
orOutputStream
. TheHttpServletResponse
class provides methods to access the header data. For example, thesetContentType
method sets the content type. (This header is often the only one manually set.)
Interacting with Clients |