
import WebSite.WinCGI.*;
public class Sample extends CGI {
public void run() throws Throwable {
Response.println("<html>\r\n<head>");
Response.println("<title>Hello</title>\r\n</head>");
Response.println("<body>\r\n<h1>Hello there!</h1>");
Response.println("</body>\r\n</html>");
}
}
Believe it or not, this is a fully functional CGI program. It sends back an HTML document with a window title and the message Hello there!. Let's look at this in more detail:
There is no need to deal with content-type headers and so forth if you are sending back HTML, because the framework defaults to text/html for response content type. It automatically sends the HTTP header when you first call one of Response's output methods. You can set a different content-type if you want, but you must do so before sending any data. Normally, you can just start sending HTML.
Note that the class name Response is used instead of the name of an instance of Response. The framework's classes work this way, similar to the way the System class works in Java. There is only one response, one request, one client, etc. So there is no need to create objects based on the CGI framework classes. Use the class names themselves. In Java terms, the framework's classes are static.
The HTML source for the form is:
<form method=POST action="/cgi-win/dummy">
<pre> Your name: <input type=text name="nm" size=20><br>
Address: <input type=text name="ad" size=40><br>
<input type=checkbox name="ck" checked>Is this cool or what?<br>
<input type=submit value="Press here to do nothing"></pre>
</form>
Note the field names nm, ad, and ck. Also, note that the form's method is POST. This is vital. Don't use GET based forms. Here is a Java CGI program that will send back the stuff in the form:
import WebSite.WinCGI.*;
public class FormEcho extends CGI {
public void run() throws Throwable {
Response.println("Your name is " + Form.getField("nm") + "<br>");
Response.println("You live at " + Form.getField("ad") + "<br>");
if(Form.getField("ck") != null)
Response.println("You think this cool! I agree.");
else
Response.println("Are you crazy? This is cool!");
}
}
Easy, isn't it? No decoding, no hassling with environment variables, INI file lines, and so on. As you may have guessed, the Form object encapsulates the data that was posted from the form. The getField() method of Form retrieves field contents by field name. Fields are assumed to contain text, and getField() returns a Java String object.
Checkboxes are special. If a checkbox is checked, it's name and (text) value appear in the posted form data. If it is not checked, it does not appear in the form at all. That's why the checkbox code above tests for null. The getField() method returns null if the named field does not exist in the posted form data.
[email protected]