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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.