HTML Forms
HyperText Markup Language (HTML) is used to create web pages
that can be viewed with a browser. There
are a number of things you can do with it, including changing the color of the
page, adding Javascript, Java applets, or VB Script, and arranging information
in lists and tables. In this document we
will see how to add html forms to the page that can be used to send information
to the server.
A markup language contains
text formatting information that tells the printer or browser how to display
the data. Html encodes this information
in tags that are started with a left
angle bracket (<) and closed with
a right angle bracket (>). Anything between the tags is treated by the
browser as formatting instructions. Tags
come in pairs, one for starting the formatting and the second for ending
it. They are nested so that one pair of
tags is completely between another.
The simplest tags are used to
create headers whose sizes range from large (h1) to small (h6). For example, <h3>This is a medium sized
header.</h3> creates a header with a size part
way between the largest and the smallest.
Forms in html begin with the
<form> tag and end with the </form> closing tag. These forms are to be filled out by the user
of the browser, and they do everything from sending in address information to
helping a buyer choose the size or color of a product.
Text Boxes and Buttons
A simple form displays some
input boxes and a button to submit the data to the server. The example below shows a complete html page
that creates a form to send the name and e-mail address to the server.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN">
<html>
<head><title>E-Mail
Form</title></head>
<body>
<h3>Enter your name and
e-mail address.
<br />Then click the
Send button to send the data to the server.</h3>
<form method = "get" action="http://127.0.0.1:8080/client_server.EmailProcessor">
<p><input type = "text" name
= "name" value = "" size = 30 /> Name </p>
<p><input type = "text" name
= "email" value = "" size = 30 /> E-Mail Address
</p>
<p><input type = "submit"
value = "Send" /></p>
</form>
</body>
</html>
Here the head tags only supply a title that will be shown at the top of the
browser when the page is loaded. The body of the document contains a message
to the user to enter data and click on the send button. The form
first supplies the method that the
server will use to process the data and the action
information that tells the server what program to use for the processing. The form displays to input text boxes and a submit
button. The type information is used to tell the browser what kind of object to
display. A text box displays a box where
the user can type in data. Its initial value is the empty string. But after data is entered, the value of the
box will be whatever was typed in. When
the type is submit, the browser displays a button with a caption given by the
value attribute.
A Java program that processes
this request follows:
package client_server;
/**
* EmailProcessor
processes a request from a web page. It
responds to the
* request by sending
back a web page listing the name and email address.
**/
import java.io.*;
import java.util.*;
import java.net.*;
public class EmailProcessor
extends WebRequestProcessor
{
String name, email;
PrintWriter out;
public void process (Request request, Response response)
{
// Get a PrintWriter object
and respond to the request.
out = response.getWriter
();
name = request.getParameter
("name");
email = request.getParameter
("email");
Page.createHeader (out,
"Addresses");
out.println
("<h3>Hello.</h3>");
out.println
("<h3>" + name+ "</h3>");
out.println
("<h3>Your email address is " + email
+ "</h3>");
Page.createFooter (out);
}
} // EmailProcessor
Radio Buttons
Another way to get
information from a form is to use radio buttons. A set of radio buttons lets the user choose
one option from a set. The example below
asks a user to indicate his or her year in college.
<body>
<h3>Display your year in college.</h3>
<form method = "get"
action="http://127.0.0.1:8080/client_server.CollegeYearProcessor">
<input type="radio" name = "year" value =
"First Year" /> Credits 0 to 31
<br /><input type = "radio"
name = "year" value = "Second Year" /> Credits 32 to 63
<br /><input type = "radio"
name = "year" value = "Third Year" /> Credits 64 to 95
<br /><input type = "radio"
name= "year" value = "Fourth Year" /> Credits 96 or over
<p><input type = "submit" value = "Send" ></p>
</form> </body>
Note the URL
string that the browser prepares for this form:
GET/ client_server.CollegeYearProcessor?year=Fourth+Year HTTP/1.1
Only one value is
sent to the server.
A Java program that processes
this request follows:
package client_server;
/**
* CollegeYearProcessor
processes a request from a web page. It
responds to the
* request by sending
back a web page listing the student's year in college.
**/
import java.io.*;
import java.util.*;
public class CollegeYearProcessor
extends WebRequestProcessor
{
public void process (Request request, Response response)
{
// Get the request parameter with type year.
String year = request.getParameter
("year");
// Get a PrintWriter object
and respond to the request.
PrintWriter out = response.getWriter ();
Page.createHeader (out,
"College Class");
out.println
("<h3>Hello.</h3>");
out.println
("<h3>Your year in college is " + year
+ "</h3>");
Page.createFooter (out);
}
} // CollegeYearProcessor
Check Boxes
Check boxes are very similar
to radio buttons. But they are
individually named rather than all having the same name. You also may select more than one choice with
a check box. The following is an example
where that would be appropriate.
<body>
<h3>Indicate your menu selections.</h3>
<form method =
"get"
action="http://127.0.0.1:8080/client_server.CheckBoxProcessor">
<input
type="checkbox" name = " menu"
value = " Hamburger" /> Hamburger
<br /><input type = "checkbox" name = " menu" value = " French Fries" />
French Fries
<br /><input type = "checkbox" name = " menu" value = " Soda" /> Soda
<br /><input type = "checkbox" name= " menu " value = " Apple Pie" />
Apple Pie
<p><input
type = "submit" value = "Send" /></p>
</form>
</body>
A simple Java program to
process this form follows:
package client_server;
/**
* CheckBoxlProcessor
processes a request from a web page that contains check boxes. It responds to the
* request by sending
back a web page listing the menu choices selected.
**/
import java.io.*;
import java.util.*;
public class CheckBoxProcessor
extends WebRequestProcessor
{
public void process (Request request, Response response)
{
// Get the choices, an array of Strings.
String [] choices = request.getParameterValues
("menu");
// Get a PrintWriter object
and respond to the request.
PrintWriter out = response.getWriter ();
Page.createHeader (out,
"Menu Choices");
out.println
("<h3>Hello.</h3>");
out.println
("<h3>Your choices are ");
// Print out the non-null values in the array.
for (int
count = 0; count < choices.length; count ++)
{
if (choices [count] !=
null)
out.println
("" + choices [count] + ", ");
}
out.println
("</h3>");
Page.createFooter (out);
}
} // CheckBoxProcessor
List Boxes
List boxes are similar to
check boxes. They have a list of options
that the user may choose from.
<body>
<h3>Indicate your menu selections.</h3>
<form method =
"get" action="http://127.0.0.1/:8080/client_server.ListBoxProcessor">
<select name = "menu" size = "4"
multiple = "multiple" >
<option /> Hamburger
<option /> Soda
<option /> French Fries
<option /> Apple Pie
</select>
<p><input type = "submit" value =
"Send" /> </p>
</form> </body>
The size attribute determines how many items will be shown. If there are more options than the number
given by size, a scroll bar is added. If
you want to allow the selection of more than one item at a time, include the multiple attribute. (In order to select several items, users have
to hold down the control key when making the selection.)
The
Request class of the simple web server must be modified to process this
form. The following code will handle the
request after the modifications have been made.
package client_server;
/**
* ListBoxProcessor
processes a request from a web page. It
responds to the
* request by sending
back a web page listing the menu choices selected.
**/
import java.io.*;
import java.util.*;
public
class ListBoxProcessor extends WebRequestProcessor
{
public void
process (Request request, Response response)
{
// Get the choices, an array of
Strings.
String [] choices = request.getParameterValues ("menu");
// Get a PrintWriter
object and respond to the request.
PrintWriter
out = response.getWriter ();
Page.createHeader
(out, "Menu Choices");
out.println
("<h3>Hello.</h3>");
out.println
("<h3>Your choices are ");
// Print out the non-null values
in the array.
for (int count = 0; count < choices.length;
count ++)
{
if
(choices [count] != null)
out.println
("" + choices [count] + ", ");
}
out.println
("</h3>");
Page.createFooter
(out);
}
} //
ListBoxProcessor
Tables
Tables
are used to display information in rows and columns. They can be used with form data, but they can
also be used elsewhere in html. Tables
are defined by the <table> </table> tags. If you want the gridlines to show, you add
the attribute, border = "1", to the table tag resulting in <table
border = "1">.
Tables
consist of rows and columns with an optional heading row. The tags for the heading row are <th></th>. The regular table rows have tags <tr></tr>
and the columns within the rows are tagged by <td></td>. All tags must be nested, that is the opening
and closing tags for a column must be completely contained within the tags for
a row. Also if the number of columns
varies from one row to the next, the display looks strange. If you want to have an empty cell, add a
non-breaking space ( ) to it. An
example of a simple table follows:
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>QPA</th>
</tr>
<tr>
<td>12-3456</td>
<td>Alice Lee</td>
<td>3.50</td>
</tr>
<tr>
<td>23-4567</td>
<td>Bill Levin</td>
<td>2.98</td>
</tr>
</table>
You should check out http://www.w3schools.com for additional
information about html. This web site
also has a very good explanation of eXtensible HTML (xhtml).
Tables can be used to display
data on an output page. The following
program has an example.
package client_server;
/**
* StudentProcessor
processes a request from a web page. It
responds to the request by
* sending back a web page listing the id, name
and qpa of the students in the class.
**/
import java.io.*;
import java.text.*;
import java.net.*;
public class StudentProcessor
extends WebRequestProcessor
{
String id, name; double qpa;
public void process (Request request, Response response)
{
// Get a PrintWriter object
and respond to the request.
out = response.getWriter
();
Page.createHeader (out,
"Class Roster");
try
{
BufferedReader infile = new BufferedReader
(new InputStreamReader (new FileInputStream
("students.txt")));
out.println
("<center><h3>Class Roster</h3>");
out.println
("<table border='1' bordercolor='#000000' cellspacing='10'>");
out.println
("<tr><td>ID</td><td>Name</td><td>QPA</td></tr>");
id = infile.readLine ();
while (id != null)
{
name = infile.readLine ();
qpa
= Double.parseDouble (infile.readLine ());
displayData
(out);
id = infile.readLine ();
}
infile.close ();
out.println
("</table></center>");
} catch (NumberFormatException
e) {}
catch (IOException
e) {System.out.println ("File not found");}
Page.createFooter (out);
} // process
// displayData displays the student
data in a row of a table.
public void displayData
(PrintWriter out)
{
out.println ("<tr><td>" + id + "</td>");
out.println
("<td>" + name + "</td>");
out.println
("<td>" + decimals (qpa) +
"</td></tr>");
} // displayData
// Formats a double for string output with two decimal places.
private String decimals (double num)
{
DecimalFormat decFor = new DecimalFormat ();
decFor.setMaximumFractionDigits
(2);
decFor.setMinimumFractionDigits
(2);
return decFor.format
(num);
} // method decimals
} // StudentProcessor
package client_server;
/**
* CheckBoxProcessor
processes a request from a web page. It
responds to the
* request by sending
back a web page listing the bill for the menu choices selected.
**/
import java.io.*;
import java.util.*;
public class CheckBoxProcessor
extends WebRequestProcessor
{
PrintWriter out;
String [] choices;
public void process (Request request, Response response)
{
// Get the choices, an array of Strings.
choices = request.getParameterValues
("menu");
// Get a PrintWriter object
and respond to the request.
out = response.getWriter
();
Page.createHeader (out,
"Test Data");
out.println
("<h3>Hello.</h3>");
out.println ("<h3>Your
Bill<br>");
double total = findTotal ();
out.println
("<h3>The total bill is " + total +
"</h3>");
Page.createFooter (out);
}
/* findTotal goes
through the entire array to find all choices that have been checked. When it finds one, it looks up the price and
adds it to the total. When done, it
returns the total. */
private double findTotal
()
{
double total = 0;
for (int
count = 0; count < choices.length; count ++)
{
if (choices [count] !=
null)
{
double price = lookUpPrice (count);
out.println
(choices [count] + ": " + price + "<br>");
total = total +
price;
}
}
return total;
} // findTotal
// loopUpPrice maintains a list of
the prices for the menu choices.
private double lookUpPrice
(int count)
{
if (choices [count].equals
("Hamburger")) return 2.50;
else if (choices
[count].equals ("French Fries")) return 1.25;
else if (choices
[count].equals ("Soda")) return 0.75;
else if (choices
[count].equals ("Apple Pie")) return 3.25;
else return 0;
} // lookUpPrice
} // CheckBoxProcessor