Cover V06, I08
Article
Listing 1
Listing 2
Listing 3
Listing 4

aug97.tar


Listing 2: GuestbookCGI.java

import java.io.*;
import java.util.*;

public class GuestBookCGI extends CGI {

public static void main(String[] argv) {
CGI cgi = new GuestBookCGI();
cgi.handle(argv);
}

protected void printBody() throws Exception {

String formURL = "GuestBookCGI";

if (getMethod().equals("POST")) {

// This is a POST, so we will process the form
// Since we want to append to the file, we use the RandomAccessFile class

RandomAccessFile guestbookFile = null;

// output the top of the page

outputStream.println("<HEAD><TITLE>Guestbook</TITLE></HEAD>");
outputStream.println("<BODY>Adding you to the guestbook...<P>");

// save the guestbook entry

guestbookFile = new RandomAccessFile("guestbook.txt","rw");
guestbookFile.seek(guestbookFile.length());
guestbookFile.writeBytes("----------------------\n");
guestbookFile.writeBytes("name="+ getValue("name") + "\n");
guestbookFile.writeBytes("email="+ getValue("email") + "\n");
guestbookFile.close();

// output confirmation

outputStream.println("<H2>Thanks " + getValue("name") + "!</H2>");

outputStream.println("<br>Guestbook Contents<br>");
DataInputStream in = new DataInputStream(new \
FileInputStream("guestbook.txt"));
String line;
while ((line = in.readLine()) != null)
outputStream.println("<br>"+line);
in.close();

outputStream.println("</BODY>");
}
else {

// This is a GET, so that means we should print out the form
// Note that if a name and/or email values are passed in
// with the GET, they will be used as default values.

outputStream.println("<HEAD><TITLE>Guestbook</TITLE></HEAD>");
outputStream.println("<BODY><H2>Please register in the \
guest book:</H2>");
outputStream.println("<FORM METHOD=POST ACTION=" + formURL + ">");
outputStream.println("Name: <input name=name value=\"" + \
getValue("name") + "\" size=20><P>");
outputStream.println("E-mail: <input name=email value=\"" + \
getValue("email") + "\" size=20><P>");
outputStream.println("<input type=submit value=\"Register in \
Guestbook\">");
outputStream.println("</BODY>");
}
}
}

// End of File