rsh aegis cd $HOME/java/class/ex10/url; setenv CLASSPATH .:$HOME/java/class:$HOME/java/class/ex3:$HOME/java/class/ex4:$HOME/java/class/ex4/foo:$HOME/java/class/ex8/sortline:$HOME/java/class/ex6/TicTacToe; /local/opt/java/bin/java Download 'http://www.javaworld.com/javaworld/jw-01-1997/jw-01-cgiscripts.html' /javaworld/jw-01-1997/jw-01-cgiscripts.html text/html
Summary
Java makes a good language choice for writing CGI programs because it is a purely object-oriented language and offers connectivity to distributed objects and database management systems. Object-oriented languages are more suitable for the creation and maintenance of larger or more complex CGI programs. Here you'll find a library of functions that will help you start writing Java CGI programs right away. This article assumes an understanding of CGI on the part of the reader, as well as experience writing a CGI program or two in a language such as Perl or C.
By Pat L. Durante
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 \ helloThis 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:
<HTML> <HEAD> <TITLE>Hello and Welcome!</TITLE> </HEAD> <BODY> <H1 ALIGN=CENTER>Hello and Welcome</H1> <hr> <FORM METHOD="POST" ACTION="/cgi-bin/hello.cgi"> What is your name? <INPUT TYPE="text" NAME="name" VALUE=""><p> What is your email address? <INPUT SIZE=40 TYPE="text" NAME="email" VALUE=""> <INPUT TYPE="submit" VALUE="Submit">. <P> </FORM> <hr> </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.
// // Parse the form data into a Hashtable. // Hashtable form_data = cgi_lib.ReadParse(System.in);
Now that we've parsed the form data, we can do whatever processing we'd
like with the data sent to us. Then we can generate some HTML to send
back to the user's browser. In this simple program, we aren't going to
do any processing with the data; we're simply going to echo back the
information supplied by the user. We are going to use the
get
method on the Hashtable object to extract the form
values into strings that we can use in our program. The following
example shows how we would extract the name that the user typed into a
String object.
String name = (String)form_data.get("name");
Now, let's put this all together in a simple program.
Here is a Java
application that we can use to process the "Hello There" form
(hello.java
):
import java.util.*; import java.io.*; class hello { public static void main( String args[] ) { // // Here is a minimalistic CGI program that uses cgi_lib // // // Print the required CGI header. // System.out.println(cgi_lib.Header()); // // Parse the form data into a Hashtable. // Hashtable form_data = cgi_lib.ReadParse(System.in); // // Create the Top of the returned HTML page // String name = (String)form_data.get("name"); System.out.println(cgi_lib.HtmlTop("Hello There " + name + "!")); System.out.println("<h1 align=center>Hello There " + name + "!</h1>"); System.out.println("Here are the name/value pairs from the form:"); // // Print the name/value pairs sent from the browser. // System.out.println(cgi_lib.Variables(form_data)); // // Print the Environment variables sent in from the Unix script. // System.out.println("Here are the CGI environment variables/value pairs" + "passed in from the UNIX script:"); System.out.println(cgi_lib.Environment()); // // Create the Bottom of the returned HTML page to close it cleanly. // System.out.println(cgi_lib.HtmlBot()); } }
Conclusion
With this introduction to CGI programming in Java, you should be on
your way to a whole new way of programming the server side of your Web
applications. Keep in mind that the CGI protocol provides only one way of
communicating between a client browser and a Web server. The World
Wide Web Consortium's Jigsaw (see the Resources section below) and others like Sun's Jeeves, are coming up with better solutions, which involve
writing Java servlets that you can hang off your Web server.
But that is a topic for another day. Have fun!
About the author
Pat
Durante is a senior software engineer at TASC, Inc. in Reading, MA. TASC is a
$300 million applied information technology company that specializes in
the development and integration of advanced information systems and
services. Pat has been engineering object-oriented applications for
four years. He is the leader of TASC's Object Oriented Special
Interest Group and the cofounder of TASC's Java Interest Group. Pat's
Web site address is: http://members.aol.com/durante.
Resources
If you have problems with this magazine, contact
webmaster@javaworld.com
URL: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-cgiscripts.html
Last updated: 15 December 1996