Chapter 4. Retrieving Information
To build a successful web application, you often need to know a lot about the environment in which it is running. You may need to find out about the server that is executing your servlets or the specifics of the client that is sending requests. And no matter what kind of environment the application is running in, you most certainly need information about the requests that the application is handling.
Servlets have a number of methods available to gain access to this information. For the most part, each method returns one specific result. If you compare this to the way environment variables are used to pass a CGI program its information, the servlet approach has several advantages:
Stronger type checking. In other words, more help from the compiler in catching errors. A CGI program uses one function to retrieve its environment variables. Many errors cannot be found until they cause runtime problems. Let’s look at how both a CGI program and a servlet find the port on which its server is running.
A CGI script written in Perl calls:
$port = $ENV{'SERVER_PORT'};where
$portis an untyped variable. A CGI program written in C calls:char *port = getenv("SERVER_PORT");where
portis a pointer to a character string. The chance for accidental errors is high. The environment variable name could be misspelled (it happens often enough) or the data type might not match what the environment variable returns.A servlet, on the other hand, calls:
int port = req.getServerPort() ...