Article
The JSP Files - Parts 1 to 8: Tagged and Bagged
Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 Next
Couch Potato
Arrays come in particularly handy when dealing with form elements like checkboxes and multiple select list boxes. Take a look at the following form, which includes a bunch of checkboxes:
<html>
<head>
<basefont face="Arial">
</head>
<body>
Pick your favourite shows:
<br>
<form action="potato.jsp" method="POST">
<input type="checkbox" name="shows" value="Ally McBeal">Ally
McBeal <input type="checkbox" name="shows" value="Buffy The
Vampire Slayer">Buffy The Vampire Slayer <input type="checkbox"
name="shows" value="The Practice">The Practice <input
type="checkbox" name="shows" value="Sex And The City">Sex
And The City <input type="checkbox" name="shows"
value="The Sopranos">The Sopranos <input type="checkbox"
name="shows" value="Survivor">Survivor <br> <input type="submit"
name="submit" value="Select"> </form>
</body>
</html>
Now, once the form is submitted, the JSP script "potato.jsp" is responsible for processing the states of the various checkboxes. Data from the checkboxes is assigned to an array, and then this array is used to recreate a list of the selected items. Take a look.
<html>
<head>
<basefont face="Arial">
</head>
<body>
So your favourite shows are:
<br>
<%
// potato.jsp - process list of selected TV shows
// define variables
String[] Shows;
// assign values to variables
Shows = request.getParameterValues("shows");
out.println("<ul>");
// print by iterating through array
for(int counter = 0; counter < Shows.length; counter++)
{
out.println("<li>" + Shows[counter]);
}
out.println("</ul>");
%>
</body>
</html>
As you can see, the first order of business is to create an array to hold the checkbox data - in this case, the array "Shows". Then, the Request object is used to obtain the values of the selected items via the
getParameterValues() method (similar to the getParameter() method, but returns a list of values, rather than a single value) and these values are then assigned to the "Shows" array. A "for" loop is then used to create a list of the selected items.
This technique can also be used with multiple select list boxes - here's the same example, rewritten to use a list box instead of a series of checkboxes.
<html>
<head>
<basefont face="Arial">
</head>
<body>
Pick your favourite shows:
<br>
<form action="potato.jsp" method="POST">
<select name="shows" multiple>
<option>Ally McBeal</option>
<option>Buffy The Vampire Slayer</option>
<option>The Practice</option>
<option>Sex And The City</option>
<option>The Sopranos</option>
<option>Survivor</option>
</select>
<br>
<input type="submit" name="submit" value="Select">
</form>
</body>
</html>
Obviously, the server-side script "potato.jsp" requires no changes at all.
Copyright Melonfire, 2000. All rights reserved.