The ServletRequest and HttpServletRequest interfaces have a ton of methods you can call, but you don’t need to memorize them all. On your own, you really should look at the full API for javax.servlet. ServletRequest and javax.servlet.http.HttpServletRequest, but here we’ll look at only the methods you’re most likely to use in your work (and which might also show up on the exam).
In the real world, you’ll be lucky (or unlucky, depending on your perspective), to use more than 15% of the request API. Don’t worry if you aren’t clear about how or why you’d use each of these; we’ll see more details on some of them (especially cookies) later in the book.
The client’s platform and browser info
String client = request.getHeader("User-Agent");
The cookies associated with this request
Cookie cookies = request.getCookies();
The session associated with this client
HttpSession session = request.getSession();
The HTTP Method of the request
String theMethod = request.getMethod();
An input stream from the request
ServletInputStream input = getInputStream();
getServerPort(), getLocalPort(), and getRemotePort() are confusing!
The getServerPort() should be obvious... until you ask what getLocalPort() means. So let’s do the easy one first: getRemotePort(). First you should ask, “remote to whom?” In this case, since it’s the server asking, it’s the CLIENT that’s the remote thing. The client is remote to the server, so getRemotePort() means “get the client’s port”. In other words, the port number on the client from which the request was sent. Remember: if you’re a servlet, remote means client.
The difference between getLocalPort() and getServerPort() is more subtle—getServerPort() says, “to which port was the request originally SENT?” while getLocalPort() says, “on which port did the request END UP?” Yes, there’s a difference, because although the requests are sent to a single port (where the server is listening), the server turns around and finds a different local port for each thread so that the app can handle multiple clients at the same time.