Using Conditionals

printer-friendly version of this section  Print  e-mail this section  E-Mail  add a public, group or private note  Add Note  add a bookmark about this section  Add Bookmark    

JSTL: JSP Standard Tag Library Kick Start
By Jeff Heaton

Table of Contents
Chapter 3.  Understanding Basic Tag Logic


Conditional statements are an important part of any programming language. These statements allow you to selectively execute parts of the program based on certain conditions. JSTL provides several tags that allow this sort of conditional execution.

JSTL's implementation of conditionals is somewhat different from Java's. In Java, your two primary conditional constructs are the if/else statement and the switch/case statement. The <c:if> and <c:choose> tags provide many of the same features, yet there are some important differences compared to their Java counterparts. We highlight these differences in this section.

In previous chapters, we have seen how the <c:if> tag can be used to make basic decisions. We now take a more in-depth look at the <c:if> tag and other conditional tags provided by JSTL. Let's begin by examining the <c:if> tag.

Using the <c:if> Tag

Nearly every programming language contains an if statement, and JSTL is no exception. The JSTL if statement is implemented using the <c:if> tag. There are two forms of the JSTL if statement:

<!-- Syntax 1: Without body content -->   <c:if test="testCondition"   var="varName" [scope="{page|request|session|application}"]/> <!-- Syntax 2: With body content -->   <c:if test="testCondition"   [var="varName"] [scope="{page|request|session|application}"]>   body content   </c:if> 

The attributes that are accepted by the <c:if> tag are as follows:

Attribute

Required

Purpose

test

Y

Specifies the test that is to be performed.

scope

N

Specifies the scope; the default is page.

var

N

Specifies the scoped variable that should receive the result of the compare. (Note: This attribute is required if the scope is present or there is no body.)

The second form demonstrates an if statement that encloses a body of code. If the expression given to the if statement evaluates to true, then that body of code is executed. Listing 3.5 shows an example of using the if statement with a body of code.

Listing 3.5 An if Statement with a Body (ifbody.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>If with Body</title>   </head>   <body>     <c:if test="${pageContext.request.method=='POST'}">       <c:if test="${param.guess=='5'}">You guessed my number!       <br />       <br />       <br />       </c:if>       <c:if test="${param.guess!='5'}">You did not guess my number!       <br />       <br />       <br />       </c:if>     </c:if>     <form method="post">Guess what number I am thinking of?     <input type="text" name="guess" />     <input type="submit" value="Try!" />     <br />     </form>   </body> </html> 

This program implements a simple number-guessing game. You are presented with a form that allows you to enter a number. When your form posts back to the page, the number you entered is compared against five. If the numbers match, you win; if the numbers do not match, you are given a chance to try again. The format of the if statement is shown here:

<c:if test="${param.guess=='5'}">   You guessed my number! </c:if> 

Most expression operators that are available in Java can also be used in a JSTL if statement. Here we are using == to request a comparison. Other operators, such as not equal(!=), greater than(>), less than(<), less than or equal(<=), and greater than or equal(>=), are also supported. With only a few minor exceptions, these operators work exactly the same as they do in Java. The most notable difference is that the equality operator(==) can be used to compare String objects. These operators are handled as part of JSTL's expression language. We cover these operators in greater detail in Chapter 4, "Using the Expression Language."

It is also possible to create an if statement that does not contain a body of code to execute. The uses for this "bodyless" statement are somewhat more limited than the general if statement. Listing 3.6 shows a program that makes use of the bodyless if statement.

Listing 3.6 An if Statement with No Body (ifnobody.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>If with NO Body</title>   </head>   <body>     <c:if test="${pageContext.request.method=='POST'}">     <c:if test="${param.guess=='5'}" var="result" />     I tested to see if you picked my number, the result was     <c:out value="${result}" />     </c:if>     <form method="post">Guess what number I am thinking of?     <input type="text" name="guess" />     <input type="submit" value="Try!" />     <br />     </form>   </body> </html> 

In Listing 3.6, the if statement stores the result of its comparison to a variable rather than conditionally executing a block of code. First the if statement is invoked; then the variable is printed.

In the following code snippet, a boolean value is stored in the scoped variable named result. When the value is printed to the browser, either true or false will be displayed:

<c:if test="${param.guess=='5'}" var="result" /> I tested to see if you picked my number, the result was <c:out value="${result}" /> 

In most programming languages, an else statement is provided to go along with the if statement. JSTL does not provide an else tag. There is a relatively simple way to produce an if/else construct, but it cannot be done with the if statement. To produce an if/else construct, you must use the <c:choose> tag. The next section will focus on this tag.

Using the <c:choose> Tag

JSTL provides you with a mutual exclusion conditional. The <c:choose> tag is called a mutual exclusion because only one block of code within the mutual exclusion will be executed. Therefore, the block of code that is chosen to execute is said to mutually exclude all other blocks of code. There is only one form of the <c:choose> tag:

<c:choose>   body content (<when> and <otherwise> subtags) </c:choose> 

No attributes are associated with the <c:choose> tag. The <c:choose> tag is almost always used with the <c:when> tag, as we discuss in the next section.

Using the <c:when> Tag

In some respects, the mutual exclusion can be compared to the switch/case or if/else tree construct in Java. The <c:choose> tag is comparable to the Java switch statement, and the <c:when> tag is comparable to the case statements of a switch statement. The general format of the JSTL mutual exclusion is shown here:

<c:when test="testCondition"> body content </c:when> 

One attribute is accepted by the <c:if> tag:

Attribute

Required

Purpose

test

Y

Specifies the test that is to be performed.

A <c:choose> tag is essentially a block of if statements. When a <c:choose> block is encountered, the <c:when> statements are evaluated in order. Once one <c:when> statement is satisfied, it is executed and the <c:choose> exits. It does not matter if more than one <c:when> statement's test is satisfied. The first <c:when> statement that is successful is the only <c:when> statement that will be executed.

The biggest difference between the <c:choose>/<c:when> tag and the switch/case statements in Java is that the <c:when> statements actually evaluate expressions. A switch/case in Java only compares a variable specified in the switch statement against constants in the case statements. This makes the <c:when> statements much more advanced than case statements.

Listing 3.7 shows an example of the mutual exclusion in action. This program shows a simple input form that asks you to enter a number. The program then responds by spelling out the name of the first five numbers after one.

Listing 3.7 Mutual Exclusion (choose.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Using Choose,Otherwise and When</title>   </head>   <body>     <c:if test="${pageContext.request.method=='POST'}">You entered:     <c:choose>       <c:when test="${param.enter=='1'}">One       <br />       </c:when>       <c:when test="${param.enter=='2'}">Two       <br />       </c:when>       <c:when test="${param.enter=='3'}">Three       <br />       </c:when>       <c:when test="${param.enter=='4'}">Four       <br />       </c:when>       <c:when test="${param.enter=='5'}">Five       <br />       </c:when>       <c:otherwise>         <c:out value="${param.enter}" />         <br />       </c:otherwise>     </c:choose>     </c:if>     <form method="post">Enter a number between 1 and 5:     <input type="text" name="enter" />     <input type="submit" value="Accept" />     <br />     </form>   </body> </html> 

If you enter a value that is not in the range of one through five, the program prints out your number in numeric form. This default behavior is provided by the <c:otherwise> tag, which we is cover in the next section.

Using the <c:otherwise> Tag

The <c:otherwise> tag provides the functionality of Java's default and else statements. The <c:otherwise> tag may only be used as part of a <c:choose> block. The following shows the general format of the <c:otherwise> tag:

<c:otherwise>   conditional block </c:otherwise> 

No attributes are associated with the <c:otherwise> tag. If you use only one <c:when> tag with a <c:otherwise> tag, you have created something that is functionally equivalent to the if/else construct. Listing 3.8 shows how the <c:otherwise> tag can be used to provide an "else" statement.

Listing 3.8 An "if" Statement with "else" (ifelse.jsp)
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html>   <head>     <title>Using Choose,Otherwise and When</title>   </head>   <body>     <c:if test="${pageContext.request.method=='POST'}">OK, we'll     send     <c:out value="${param.enter}" />     <c:choose>       <c:when test="${param.enter=='1'}">pizza.       <br />       </c:when>       <c:otherwise>pizzas.       <br />       </c:otherwise>     </c:choose>     </c:if>     <form method="post">Enter a number between 1 and 5:     <input type="text" name="enter" />     <input type="submit" value="Accept" />     <br />     </form>   </body> </html> 

The code in Listing 3.8 asks in a form how many pizzas you would like to order. The program then prints the message "OK, we'll send xxx pizza(s)." The if/else construct is used to cause the program to print out the word pizza if only one pizza is being ordered and to print out the word pizzas if more than one is ordered. The following block of code implements the if/else construct:

<c:choose>   <c:when test="${param.enter=='1'}">     pizza.   </c:when>   <c:otherwise>     pizzas.   </c:otherwise> </c:choose> 

As you can see, a <c:when> tag is used to evaluate whether the order is equal to one. If the order is equal to one, then the program prints the word pizza. If the order is not equal to one, then the word pizzas is printed.

Nesting Conditionals

Like any other programming language, JSTL allows you to nest conditionals. All JSTL tags are XML-style tags. You nest conditionals in JSTL by nesting their XML tags. For example, the following shows two if statements nested:

<c:if test="${pageContext.request.method=='POST'}">   <c:if test="${param.guess=='5'}">     You guessed my number!   </c:if> </c:if> 

Conditionals can be nested very deep. You can also nest different conditionals within each other. For example, it is completely valid to nest a <c:if> tag inside a <c:when> tag.


    printer-friendly version of this section  Print  e-mail this section  E-Mail  add a public, group or private note  Add Note  add a bookmark about this section  Add Bookmark    
    Top

    [0672324504/ch03lev1sec2]

     
     


    JSTL. JSP Standard Tag Library Kick Start
    JSTL: JSP Standard Tag Library Kick Start
    ISBN: 0672324504
    EAN: 2147483647
    Year: 2001
    Pages: 93
    Authors: Jeff Heaton

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net