Newsletter sign-up

Sign up for our technology specific newsletters.

Enterprise Java
View all newsletters

Email Address:

Write CGI programs in Java

Learn how to program the server side of your Web applications through Java

The Common Gateway Interface (CGI) is a standard for writing programs that can interact through a Web server with a client running a Web browser. These programs allow a Web developer to deliver dynamic information (usually in the form of HTML) via the browser. A CGI program can be written in any language, including Java, that can be executed by your Web server. CGI programs are commonly used to add search engines, guest-book applications, database-query engines, interactive-user forums, and other interactive applications to Web sites.

In very basic terms, a CGI program must interpret the information sent to it, process the information in some way, and generate a response that will be sent back to the client.

Most of the input to a CGI program is passed into it through environment variables. This article will demonstrate how to send these environment variables to a Java CGI program. The rest of the input (if any) is passed into a CGI program as standard input that can be read directly by your program.

The processing can be as simple as appending information to a file or as complex as requesting data from a database.

Since a CGI program can return a myriad of document types, a CGI program must place a short header (ASCII text) on its output so that the client will know how to interpret the information it generates. Most commonly, CGI programs generate HTML. Below, you will find a library of functions including one that generates the appropriate header for HTML. Following the header, a CGI program simply generates the body of the output in its native form.

Passing the CGI environment into the Java program

Writing a CGI program in Java is fairly easy to do once you understand the issues. First and foremost, you need to wrap the execution of the Java program inside another script. So, the actual script invoked on your Web server will be a Unix shell script or a Windows batch file (or equivalent) that simply passes the CGI environment variables into your Java program.

Since Java no longer provides a method to access environment variables directly (the System.getenv() method has been disabled in the latest release of the JDK), I propose passing each CGI environment variable into the Java program using the -D command-line parameter on the Java interpreter. I will show you how to use the -D parameter below.

The library of functions I provide below assumes that you have used the approach described above; it uses the System.getProperty() method to access those command-line parameters. If your program needs to use any of the CGI environment variables, you can access them the same way. For example, if you want to access the SERVER_NAME environment variable, you could do so as follows:

    String server_name = System.getProperty("cgi.server_name");


Be aware that I am not passing all of the CGI environment variables into my Java program. I'm only passing the major ones. I'll leave the inclusion of the others as an exercise for the reader.

The following example shows a Unix script file called hello.cgi invoking a Java program called hello. Note that the -D command-line parameter passes the CGI environment variables into the Java program:

#!/bin/sh
java     -Dcgi.content_type=$CONTENT_TYPE     -Dcgi.content_length=$CONTENT_LENGTH     -Dcgi.request_method=$REQUEST_METHOD     -Dcgi.query_string=$QUERY_STRING     -Dcgi.server_name=$SERVER_NAME     -Dcgi.server_port=$SERVER_PORT     -Dcgi.script_name=$SCRIPT_NAME     -Dcgi.path_info=$PATH_INFO   hello


This solution doesn't work well on the Windows 95 and NT platforms because there may be limits on the number of characters allowed on the command line. An alternative approach might be simply to write each of the environment variables and their associated values to a temporary file (with a unique filename, of course). Then, you may pass the name of this file into your Java program and have it read that file and parse out the environment variable/value pairs. Don't forget to delete the temporary file when you're done using it! Again, this exercise is left to the reader.

A Java CGI library

To ease the tedious task of processing the CGI inputs, I have written a Java class (really a library of functions) that you can utilize to cut down on some of the dirty work. This library attempts to duplicate the functionality in the very popular Perl cgi-lib.pl library. I have documented the code below using javadoc-style comments so that you can generate HTML documentation directly from the code. (Use javadoc cgi_lib.java to generate cgi_lib.html.)

Here is the source code and documentation for the library.

Writing your first Java CGI program

Here's an example that shows how the cgi_lib.java library can be used to write a CGI program. We'll write a simple program that processes my "Hello There" form. This simple form will prompt the user for a name and email address. Here is the form (hello.html) that we want to process:

&ltHTML>
&ltHEAD>
&ltTITLE&gtHello and Welcome!</TITLE>
</HEAD>
&ltBODY>
&ltH1 ALIGN=CENTER&gtHello and Welcome</H1>
&lthr>
&ltFORM METHOD="POST"
      ACTION="/cgi-bin/hello.cgi">
 What is your name?
 &ltINPUT TYPE="text" NAME="name" VALUE="">&ltp>
 What is your email address?
 &ltINPUT SIZE=40 TYPE="text" NAME="email" VALUE="">
 &ltINPUT TYPE="submit" VALUE="Submit"&gt.   &ltP>
</FORM>
&lthr>
</BODY>
</HTML>


Let's write a Java program to process the "Hello There" form.

First, we need to let the client know that our program will be generating HTML. The Header() method in cgi_lib.java creates the string we need, so we'll start by calling that method and sending the string to standard out using the System.out.println system call.

    //
    //  Print the required CGI header.
    //
    System.out.println(cgi_lib.Header());


Second, we want to process the form data sent to us by the browser. The ReadParse method in cgi_lib.java does all that work for us and returns the result in an instance of a Hashtable. In this case, the Hashtable will contain two key values after parsing the form data. One will be the "name" input field and the other will be the "email" input field. The values associated with each of these keys will be whatever the user typed into those input fields on the "Hello There" form.

Resources