JSP/Servlet | JSTL(JSP Standard Tag Library) | Conditionals <c:if>, <c:choose>, <c:when>, <c:otherwise>

Let’s look at conditional statements in JSTL.

Conditional <c:if>

In JSTL, conditions are written with <c:if> ~ </c:if>. One thing to note is that, unlike other languages, there is no else.

Attribute descriptions

Item Description Required Default
test Condition to evaluate Required
var Name of the variable that stores the condition result
scope Scope of the variable that stores the condition result page

Example

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
    <title><c:if> Tag Example</title>
</head>
<body>
    <c:set var="aaa" value="1" scope="session"/>
    <c:if test="${aaa == 1}">
        <p>a is 1.<p>
    </c:if>
</body>
</html>

Result

a is 1.

Conditionals <c:choose>, <c:when>, <c:otherwise>

<c:choose> selects one of several conditions, similar to switch-case in Java. <c:choose> corresponds to switch, <c:when> corresponds to case, and <c:otherwise> corresponds to default.

Attributes

  • The <c:choose> tag has no attributes.
  • The <c:when> tag has one attribute listed below.
  • The <c:otherwise> tag has no attributes.
Item Description Required Default
test Condition to evaluate Required

Example

<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>

<html>
<head>
      <title><c:choose> Tag Example</title>
</head>
<body>
    <c:set var="a"  value="${256}" scope="session"/>
    <c:set var="result" value="${a % 3}" scope="session"/>

    <c:choose>
        <c:when test="${result == 1 || salary == 2}">
            ${a} is not a multiple of 3.
        </c:when>         
        <c:otherwise>
           ${a} is a multiple of 3.
         </c:otherwise>
    </c:choose>
   
</body>
</html>

Result

${a} is not a multiple of 3.

Comparison expressions: eq, ne, empty

When using conditionals, you must compare values. In JSTL, comparison expressions such as eq, ne, and empty can be used.

Expression Symbol Description
eq == Used to check whether compared values are the same.
ne != Used to check whether compared values are not the same.
empty == null Used to check whether the compared value is null. To express a non-null case, use !empty.

eq (==) example

<c:if test="${list eq null}">...</c:if> <!-- null comparison -->
<c:if test="${int eq 0}">...</c:if> <!-- number comparison -->
<c:if test="${str eq 'a'}">...</c:if> <!-- string comparison -->

ne (!=) example

<c:if test="${list ne null}">...</c:if> <!-- null comparison -->
<c:if test="${int ne 0}">...</c:if> <!-- number comparison -->
<c:if test="${str ne 'a'l}">...</c:if> <!-- string comparison -->

empty (== null) example

<c:if test="${empty list}">...</c:if> <!-- when the collection object is empty -->
<c:if test="${!empty list}">...</c:if> <!-- when the collection object is not empty -->