background image

Conditional Tags

<< Flow Control Tags | Iterator Tags >>
<< Flow Control Tags | Iterator Tags >>

Conditional Tags

(ShoppingCartItem)i.next();
...
%>
<tr>
<td align=
"right" bgcolor="#ffffff">
${item.quantity}
</td>
...
<%
}
%>
Flow control tags eliminate the need for scriptlets. The next two sections have examples that
demonstrate the conditional and iterator tags.
Conditional Tags
The if tag allows the conditional execution of its body according to the value of the test
attribute. The following example from
tut-install/javaeetutorial5/examples/web/bookstore4/web/books/bookcatalog.jsp tests
whether the request parameter Add is empty. If the test evaluates to true, the page queries the
database for the book record identified by the request parameter and adds the book to the
shopping cart:
<c:if test=
"${!empty param.Add}">
<c:set var=
"bid" value="${param.Add}"/>
<jsp:useBean id=
"bid"
type=
"java.lang.String" />
<sql:query var=
"books"
dataSource=
"${applicationScope.bookDS}">
select * from PUBLIC.books where id = ?
<sql:param value=
"${bid}" />
</sql:query>
<c:forEach var=
"bookRow" begin="0" items="${books.rows}">
<jsp:useBean id=
"bookRow" type="java.util.Map" />
<jsp:useBean id=
"addedBook"
class=
"database.Book" scope="page" />
...
<% cart.add(bid, addedBook); %>
...
</c:if>
The choose tag performs conditional block execution by the embedded when subtags. It renders
the body of the first when tag whose test condition evaluates to true. If none of the test
conditions of nested when tags evaluates to true, then the body of an otherwise tag is evaluated,
if present.
For example, the following sample code shows how to render text based on a customer's
membership category.
Core Tag Library
Chapter 7 · JavaServer Pages Standard Tag Library
207