Now that the basics are done with, it's time to begin applyingthat theory to Web development. This week, The JSP Files investigates theJSP Request object, and demonstrates how it can be used to process formdata. Learn about JSP's array variables, find out what chocolate chipcookies and couch potatoes have in common, and explore a very unusualpharmacy.
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 variablesString[] Shows;// assign values to variablesShows = request.getParameterValues("shows");out.println("<ul>");// print by iterating through arrayfor(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.