Using JSTL Conditionals

JSTL provides all basic conditionals to make the logic flow of JSP page easier to read and maintain. The conditionals include: if condition and looping condition.

<c:if> action

The most basic and simplest condition is <c:if> action. The <c:if> action is used to output its body content based on a Boolean expression. If the result of the expression is true, the body content will be processed by JSP container and output will be returned to the current JspWriter. The syntax of <c:if> action is as follows:

<c:if test="expression">
<%-- body content listed here --%>
</c:if>Code language: HTML, XML (xml)

The expression is evaluated in the attribute test. Let’s take a look at an example of using <c:if> action:

<jsp:useBean id="cal"
             class="java.util.GregorianCalendar" />

<c:set var="hour" value="${cal.time.hours}" />

<c:if test="${hour >=0 && hour <=11}">
   <c:out value="Good morning" />
</c:if>

<c:if test="${hour >=12 && hour <=17}">
   <c:out value="Good Afternoon" />
</c:if>

<c:if test="${hour >=18 && hour <=23}">
   <c:out value="Good Evening" />
</c:if>Code language: JavaScript (javascript)

First, we create an object cal which is an instance of class java.util.GregorianCalendar. Then we set the hour property of that object to hour variable. Finally, we use the <c:if> action to determine the period in a day to output the corresponding greeting message.

Multiple choices with <c:choose> <c:when> and <c:otherwise> actions

If you have a set of mutually conditions you can use <c:choose> <c:when> and <c:otherwise> instead of using multiple <c:if>. Here is the usage of those actions:

<c:choose>
<c:when test="expression1">
<%-- body content for expression 1  -->
</c:when>
<c:when test="expression2">
<%-- body content for expression 2  -->
</c:when>
...
<c:otherwise>
<%-- body content for otherwise  -->
</c:otherwise>
</c:choose>Code language: HTML, XML (xml)

In a range of conditions, if one of them is evaluated as true, the body content of that <c:when> branch will process and output to the current JspWriter and then no processing is performed. If none of conditions in <c:when> branch is true, the body content of <c:otherwise> branch will process and output to the current JspWriter. The combination of <c:choose> <c:when> and <c:otherwise> actions works like if elseif and else condition.

Let’s rewrite the above example by using <c:choose> <c:when> and <c:otherwise> actions

<jsp:useBean id="cal"
             class="java.util.GregorianCalendar" />

<c:set var="hour" value="${cal.time.hours}" />

<c:choose>
    <c:when test="${hour >=0 && hour <=11}">
<c:out value="Good morning" />
    </c:when>
    <c:when test="${hour >=12 && hour <=17}">
<c:out value="Good Afternoon" />
    </c:when>
    <c:otherwise>
<c:out value="Good Evening" />
    </c:otherwise>
</c:choose>Code language: JavaScript (javascript)