O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Making an Applet Run a CGI Script

Problem

You want an applet to run a CGI script.

Solution

Just use showDocument( ) with the correct URL.

Discussion

It doesn’t matter what type of target your URL refers to. It can be an HTML page, a plain text file, a compressed tar file to be downloaded, a CGI script, servlet, or JavaServer Page (Chapter 18). In all cases, you simply provide the URL. The Java applet for this appears in Example 17-4.

Example 17-4. TryCGI.java

/** 
 * Try running a CGI-BIN script from within Java. 
 */ 
public class TryCGI extends Applet implements ActionListener { 
    protected Button goButton; 
 
    public void init(  ) { 
        add(goButton = new Button("Go for it!")); 
        goButton.addActionListener(this); 
    } 
 
    public void actionPerformed(ActionEvent evt) { 
        try { 
            URL myNewURL = new URL("http://server/cgi-bin/credit"); 
 
            // debug... 
            System.out.println("URL = " + myNewURL); 
 
            // "And then a miracle occurs..." 
            getAppletContext(  ).showDocument(myNewURL); 
 
        } catch (Exception err) { 
            System.err.println("Error!
            showStatus("Error, look in Java Console for details!"); 
        } 
    } 
}

Since this is an applet, it requires an HTML page to invoke it. I used the HTML shown here:

<HTML><HEAD> <TITLE>Java Applets Can Run CGI's (at least on Netscape Navigator)</TITLE> <BODY BGCOLOR="White"> <H1>Java Applets Can run CGI's (at least on Netscape Navigator)</H1> <P>Click on the button on this little Applet for p(r)oof! <APPLET CODE="TryCGI" WIDTH=100 HEIGHT=30> <P>If you can see this, you need to get a Java-powered(tm) Web Browser ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required