The Java EE 5 Tutorial

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.

<c:choose>
     <c:when test="${customer.category == ’trial’}" >
         ...
     </c:when>
     <c:when test="${customer.category == ’member’}" >
         ...
     </c:when>
         <c:when test="${customer.category == ’preferred’}" >
         ...
     </c:when>
     <c:otherwise>
         ...
     </c:otherwise>
 </c:choose>

The choose, when, and otherwise tags can be used to construct an if-then-else statement as follows:

<c:choose>
     <c:when test="${count == 0}" >
         No records matched your selection.
     </c:when>
     <c:otherwise>
         ${count} records matched your selection.
     </c:otherwise>
 </c:choose>