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:

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

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:

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

  • Was this tutorial helpful ?
  • YesNo