JSP JSTL Core Tags – contd.

JSTL IF Tag

The If tag evaluates an expression and displays its body content only if the expression evaluates to true. In the example, we are going to display “Special Discount” if a student is a gold customer.

Code Example

<c:if test="${tempStudent.goldCustomer}">

    Special Discount

</c:if>

Explanation

So this code basically is just checking whether a student is a gold customer or not. Now remember JSP will automatically call the tempStudent.isgoldCustomer method. When called this method will return the Boolean value. If the returned value is true, the code displays the content mentioned in the body of the “if” tag. If the test returns false, you won’t get anything.

It is important to remember that this “if” tag isn’t like your regular expression from any other programming language. You don’t get an else tag.

JSTL Choose Tag

So JSTL has a choose tag, which is very much similar to a regular switch statement. So we can test some conditions and they’ll have an “otherwise” or a “default” handler. Let’s explore a couple of examples to have a better understanding of how it works.

Code Example

<c:choose>

<c:when test="${temStudent.goldCustomer}">

    Special Discount

</c:when>

<c:otherwise>

        //Add anything here

</c:otherwise>

</c:choose>

Explanation

So we open up a choose tag and then add the conditions. We start adding the conditions with a “when” sub-tag and then an “otherwise” sub-tag. So we start specifying the conditions with “when” and then we can go ahead and add as many when conditions as we want, finally followed by an otherwise tag specifying the behavior in case none of the specified conditions aren’t fulfilled.

So in the example above, we have started off the conditions by checking whether a student is a gold customer or not. If they are one, Special Discount is displayed, otherwise, anything else will be displayed. You can add anything you want done.

In essence, it’s like an “if-else” statement.

Series Navigation<< JSP JSTL Core Tags

Leave A Comment

Your email address will not be published. Required fields are marked *