Java Servlets   «Prev  Next»

Lesson 4Implementing Server Side technologies using CGI
Objective Explain how CGI works.

Explain how the Common Gateway Interface works

CGI stands for Common Gateway Interface.
It is not a program at all, but a set of rules for the way a Web server can deliver information to a program running on the same machine, and receive information from the program when completed.
For example, perhaps a user will fill out a form on your Web site requesting more information about your products or services.
He types his name, address, and so on into fields on an HTML form, then submits the form.
The ACTION parameter on the form identifies a program on the server.
The browser includes all the form values in the path and file name it sends to the Web server, like this:
GET /cgi/info-request.cgi?name=Tom&phone=2990633 HTTP/1.0

The Web server starts the CGI program running (request.cgi) and sends all the form values to it (name=Tom&phone=2990633).
The CGI program does something useful, such as updating a database, or sending email, then writes out HTML. The Web server sends the HTML back to the browser to be rendered for the user.
You have to write all the HTML for the whole page, even if most of the page is the same throughout your site.
If you change the look of your site, you will have to change the CGI code to generate the new look.
ACTION parameter: The attribute on an HTML FORM tag that names the program to be run on the server when the form is submitted by the user.

The Advantages of Servlets Over CGI

Java servlets are more efficient, easier to use, more powerful, more portable, safer, and cheaper than traditional CGI and many alternative CGI-like technologies.

Efficient

With traditional CGI, a new process is started for each HTTP request. If the CGI program itself is relatively short, the overhead of starting the process can dominate the execution time. With servlets, the Java virtual machine stays running and handles each request with a lightweight Java thread, not a heavyweight operating system process. Similarly, in traditional CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. With servlets, however, there would be N threads, but only a single copy of the servlet class would be loaded. This approach reduces server memory requirements and saves time by instantiating fewer objects. Finally, when a CGI program finishes handling a request, the program terminates. This approach makes it difficult to cache computations, keep database connections open, and perform other optimizations that rely on persistent data. Servlets, however, remain in memory even after they complete a response, so it is straightforward to store arbitrarily complex data between client requests.

It is challenging to maintain state with CGI, but it can be done.
Problems regarding CGI will be discussed in the next lesson.