Most JavaServer Pages will need to perform one of several actions according to some condition. This is managed in the code through control statements, which come in three flavors: conditional, iterative, and branching. This article will explain the syntax Java provides for these statements, how and when to use arrays, and more. It is taken from chapter five of Beginning JSP 2 From Novice to Professional, written by Peter den Haan et. al. (Apress, 2004; ISBN: 1590593391).
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:
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:
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:
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.