Popular Posts

Monday, April 13, 2009

Accessing the Standard CGI Variables

Accessing the Standard CGI Variables:

To build the 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 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 the information about the requests that the application is handling.

Advantages of Using Servlets Over CGI

* Stronger type checking. In other words, more help from compiler in catching errors. A CGI program uses one function to retrieve its environment variable. Many errors cannot be found until they cause runtime problem. Let's look at how both a CGI program and servlets find the port on which its server is running.

A CGI script written in Perl call: $port = $ENV{'SERVER_PORT'}; port is an untyped variable. A CGI program written in C call: The chance for accidental errors is also high. The environment variable name could be misspelled or the data type might not match what the environment variable returns.

A servlet, on the other hand, call:

int port = req.getServerPort()

This eliminates a lot of the accidental errors because the compiler can guarantee there are no misspellings and each return type is as it should be.
*

Delayed calculation. When the server launches a CGI program, the value for each and every environment variable must be precalculated and passed, whether the CGI program uses it or not. A server launching the servlets has the option to improve performance by delaying these calculations and performing them on demand as needed.
*

More interaction with server. Once the CGI program begins execution, it is untethered from its server. The only communication path available to program is its standard output. A servlet, however, can also work with the server. As discussed in the last chapter, a servlet operates either within the server (when possible) or as connected process outside the server (when necessary). Using this connectivity, a servlet can make ad hoc requests for calculated the information that only the server can provide. For example, a servlet can have its server do arbitrary path translation, taking into consideration the server's aliases and virtual paths.



CGI Environment Variables and the Corresponding Servlet Methods











CGI Environment VariableHTTP Servlet Method
SERVER_NAMEreq.getServerName()
SERVER_SOFTWAREgetServletContext().getServerInfo()
SERVER_PROTOCOLreq.getProtocol()
SERVER_PORTreq.getServerPort()
REQUEST_METHODreq.getMethod()
PATH_INFOreq.getPathInfo()
PATH_TRANSLATEDreq.getPathTranslated()
SCRIPT_NAMEreq.getServletPath()
DOCUMENT_ROOTreq.getRealPath("/")

No comments:

Post a Comment