Servlet Requests

When a servlet is asked to handle a request, it typically needs specific information about the request so that it can process the request appropriately. Most frequently, a servlet will retrieve the value of a form variable and use that value in its output. A servlet may also need access to information about the environment in which it is running. For example, a servlet may need to find out about the actual user who is accessing the servlet, for authentication purposes.

The ServletRequest and HttpServletRequest interfaces provide access to this kind of information. When a servlet is asked to handle a request, the server passes it a request object that implements one of these interfaces. With this object, the servlet can determine the actual request (e.g., protocol, URL, type), access parts of the raw request (e.g., headers, input stream), and get any client-specific request parameters (e.g., form variables, extra path information). For instance, the getProtocol( ) method returns the protocol used by the request, while getRemoteHost( ) returns the name of the client host. The interfaces also provide methods that let a servlet get information about the server (e.g., getServername( ), getServerPort( )). As we saw earlier, the getParameter( ) method provides access to request parameters such as form variables. There is also the getParameterValues( ) method, which returns an array of strings that contains all the values for a particular parameter. This array ...

Get Java Enterprise in a Nutshell, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.