Making Decisions, Decisions - Trying It Out: Working with the choose...when...when Construct
(Page 8 of 11 )
To use the choose...when...when construct, follow these steps:
You’ll create an HTML file to build the initial form displayed to the user. Call this file whenexample2.html, and place it in your Decisions folder. It starts out identically to your previous HTML file:
<html>
<head>
<title>Conditional Statements</title>
</head>
<body>
As before, you create an HTML form, containing a table, that will post its data to a JSP:
<form method="POST" action="whenexamplehandler2jsp">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td><b>View Fruit Details</b></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="3">
This time, you create a drop-down list, with the following HTML:
<select size="1" name="fruit">
<option selected value="1">Orange</option>
<option value="2">Apple</option>
<option value="3">Pear</option>
</select>
You need a submit button again, this time labeled Get Details:
<input type="submit" value="Get Details" name="GetDetailsBtn" />
</td>
</tr>
</table>
</form>
</body>
</html>
When the user clicks the Get Details button, they’ll be passed to the whenexamplehandler2.jsp file. This is fairly short and appears as follows in its entirety:
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
<title>Decisions Examples</title>
</head>
<body>
<b>Fruit Details Page</b><br /><br />
<c:choose>
<c:when test="${param.fruit eq 1}" >
Orange<br />
Price : $0.30, Color: Orange<br />
</c:when>
<c:when test="${param.fruit eq 2}" >
Apple<br />
Price : $0.35, Color: Red<br />
</c:when>
<c:when test="${param.fruit eq 3}" >
Pear<br />
Price : $0.50, Color: Brown<br />
</c:when>
</c:choose>
</body>
</html>
Now browse to localhost:8080/Decisions/whenexample2.html in your browser. Select a fruit from the drop-down list, as shown in Figure 5-6.

Figure 5-6. Choose a fruit.
If you choose Apple and click Get Details, you’ll see the information shown in Figure 5-7.

Figure 5-7. The chosen fruit’s details are displayed.
How It Works
The fruit selected in the initial HTML page is stored in a form field called fruit, and you use it in the test attribute of JSTL <when> tags in your JSP page:
<c:when test="${param.fruit eq 2}" >
Apple<br />
Price : $0.35, Color: Red<br />
</c:when>
Notice the JSTL relational operator eq, which has the same function as the equals sign. Also note the similarity between the <c:when> tag and the case statement in Java’s switch construct.
Next: Understanding Loops and Iteration >>
More Java Articles
More By Apress Publishing
|
This article was excerpted from Beginning JSP 2: From Novice to Professional by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391). Check it out at your favorite bookstore. Buy this book now.
|
|