Sie sind hier

The Java Framework for CGI

Gespeichert von Marc Balmer am Mo., 01/01/1996 - 01:00

(This document describes version 1.01 of the framework) Copyright © 1996 by Marc Balmer, CH-4055 Basel, Switzerland. Internet applications written in the Java programming language are mostly designed as applets that run in a Java enabled browser like Netscape. There are, however, still many web-browser around that don't support Java. These need to use CGI (Common Gateway Interface) to access interactive pages on the web. Although CGI programs traditionally were realized using a scripting language like Perl or even the Bourne shell, nothing speaks against using Java to write CGI program.

Purpose of a CGI Framework

Clearly a application framework should relief the programmer from routine task. A framework should contain most or all code that is common to a certain kind of application. The CGI framework thus needs to perform the following tasks:

  • Provide access to the environment variables supplied by the web-server
  • Parse form data
  • Provide access to the parsed form data
  • Provide means to output HTML code in return of a form action

NB: Some of the above listed points seem trivial, e.g. accessing the environment variables. Java programmers should be aware that they cannot access the environment variables of the underlying operating system directly. Instead a Java-Wrapper which actually calls the Java program, will be provide the necessary environment variables in the system properties list. A more technical discussion of the needed Java-Wrapper can be found in "Using Java for CGI Programs".

Using the Framework

The framework consist of one class, CGIApplication, that contains all necessary methods. An application using the framework will therefore need to extend this class.

Step 1: Create a subclass of the CGIApplication class

You create a subclass of the CGIApplication class. This class will be the main class of your CGI application:

  import hpti.cgi.*;

  public class MyCGIApp extends CGIApplication {
  }

Step 2: Supplying a main() method

You must supply a public void static main() method in the class derived from CGIApplication. This method must at least create a new object of of your CGI application class and call its run() method to start-up the framework code:

  public static void main(String argv[]) {
    MyCGIApp app = new MyCGIApp();
    app.run(argv);
  }

Step 3: Supplying a process() method

In order to finish the application you must supply the process() method of your application. The process() method will be called by the framework after it has setup everything and parsed form input. process() is where your application takes place.

  public void process() {
    // Application specific code
  }

The process() method

The process() method of classes derived from CGIApplication is the core of your application. I will describe in detail all the public methods of the framework that you can access.

Accessing Server supplied CGI environment variables

A Java program has no access to environment variables. There is no getenv() method like in C or C++. Therefore environment variables are placed in the system properties list, where they can easily be accessed. The name of the environment variables remains unchanged. To access a server environment variable, e.g. QUERY_STRING, you must first get the system properties. The, using the getProperty() method, you get the value of a certain property:

  Properties p = System.getProperties();
  String query = p.getProperty("QUERY_STRING");

If the environment variable QUERY_STRING had not been set, the getProperty() method returns null.

Accessing form data

If your application has been called in response to a HTML form action, there will be form input available for retrieval. Form input is accessed using the get() and getCheckbox() methods. The following example assumes that the form, from which from data has been posted, contained a input field named "Foo" and a checkbox named "Bar". In the "Foo" input field the user typed "wizard". The example code

  String foo = new String(get("Foo"));
  boolean bar = getCheckbox("Bar"));

will set the variables foo and bar as follows: foo = "wizard" and bar = true. If you try to access a non-existent field, e.g. a field whose name is unknown, the get() method will return null. NB: As of the time of this writing, the CGI framework only support form POST actions.

Generating HTML output

In response to form actions a CGI program normally creates HTML output. To aid the programmer in creating syntactically correct HTML code, a class library for HTML output has been developed by the author. This class library is described in a separate document. This is why only the methods that pertain directly to the CGIApplication framework are described here. For an in-depth discussion of the HTML class library, refer to the correspondent document.

 

Technical note: Although the CGIApplication class bears the same method interface as the HTML Container class, it is not derived from the Container class. Instead the CGIApplication aggregates a Container object (namely of class Document) and delegates all messages to this object. Object composition was used instead of inheritance.

Setting and Querying the Title of the Output Document

You use the setTitle() method to set the title of the generated output document. To set the title to "Sample CGI Application" you would use the following method call:

  setTitle("Sample CGI Application");

To query the currently set title you use the getTitle() method:

  String title = getTitle();

Adding a HTML Component

You add a HTML Component to the current output document by using the add() method. To add a Heading 1 with the text "Sample CGI Application" you would use the following code:

  add(new Heading(1, "Sample CGI Application"));

Output the HTML Code

To output the HTML document you must provide a java.io.PrintStream object to the show() method of the framework. Although you will mostly use the System.out object as the PrintStream, nothing prohibits you from using any other PrintStream object like e.g., a file. The normal case, however, will be to use the following code:

  show(System.out);

An Example Application

The following example CGI program will output an initial page with one input field. As soon as the user enters text an presses the OK button, it will be called again and process the input. The output created will simply show what the user entered:

Sample CGI Application

Foo

When the user type "wizard" int the Foo input field, the output will thus be the following:

Sample CGI Application

The user typed 'wizard' in the Foo input field.

The Sample CGI Application Source Code

/**
* CGI Application Framework example
* @author Marc Balmer
* @version 1.01
*/

import java.util.*;

import hpti.cgi.*;
import hpti.html.*;

public class CGIExample extends CGIApplication {

  /**
  * The main() method creates a new CGIExample object and calls the run() method
  */
       
  public static void main(String argv[])
  {
    CGIExample app = new CGIExample();
    app.run(argv);
  }

  /**
  * process() is where it all happens
  */
       
  public void process()
  {
    // Get the system properties       
    Properties p = System.getProperties();
       
    // Find the QUERY_STRING variables
    String query = p.getProperty("QUERY_STRING");
       
    // If QUERY_STRING is set to Input, assume form input, 
    // else display an initial page
    if (query != null && query.equals("Input"))
      WorkPage();
    else
      InitialPage();
  }
       
  /**
  * Show the initial page when this program is
  * called without a QUERY_STRING
  */
       
  public void InitialPage()
  {
    // Set the title of this document and add a header
    setTitle("Sample CGI Application");
    add(new Heading(1, "Sample CGI Application"));
       
    // Create a new form with the Foo input field
    Form f = new Form("CGIExample?Input", "post");
       
    // Add the input field to the form
    f.add("Foo ");
    f.add(new Input("Foo"));
       
    // Add a paragraph to the form
    f.add(new Paragraph());
       
    // Now add a submit and a reset button
    f.add(new SubmitButton("OK"));
    f.add(new ResetButton("Cancel"));
       
    // Add the form to the document
    add(f);

    // Show the document       
    show(System.out);
  }

  /**
  * Show the work page, i.e. the page that is called
  * in response to a form POST action
  */
       
  public void WorkPage()
  {
    // Set the title of this document and add a header
    setTitle("Sample CGI Application");
    add(new Heading(1, "Sample CGI Application"));
       
    // Add what the user typed in the Foo input field
    add("The user typed '" + get("Foo") + "' in the Foo input field.");

    // Now show the page
    show(System.out);
  }
       

}

Limitations of this Version of the Framework

This version of the CGI framework only parses form POST input. Form GET input is not parsed. Consequently you must not use the form GET method with this version of the framework.

Future enhancements

A next release of the CGI framework will introduce some enhancements:

  • The form GET method will be supported
  • Accessing unknown input fields will throw an exception
  • The HTML helper class library will be more complete

Related Documents

A more technical description on how Java can be used for CGI programs can be found in "Using Java for CGI Programs". This paper discusses how to set-up an environment for Java programs on a web-server.