How to use the if else option in JSTL

Posted by leeroy1 on Tue, 17 Mar 2020 17:30:25 +0100

Is there an if else tag in JSTL?

#1 building

In addition to the skaffman answer, a simple if else can use a ternary operator like this

<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>

#2 building

No if else, just.

<c:if test="${user.age ge 40}">
 You are over the hill.
</c:if>

You can choose to use choose when:

<c:choose>
  <c:when test="${a boolean expr}">
    do something
  </c:when>
  <c:when test="${another boolean expr}">
    do something else
  </c:when>
  <c:otherwise>
    do this when nothing else is true
  </c:otherwise>
</c:choose>

#3 building

I used only two if tags, thinking I would add an answer to prevent others from using it:

<c:if test="${condition}">
  ...
</c:if>
<c:if test="${!condition}">
  ...
</c:if>

Although the behavior of if else itself is not the same technically, choose tags in a cumbersome way to avoid use, so depending on how complex your requirements are, it may be desirable.

#4 building

Yes, but clumsy, for example

<c:choose>
  <c:when test="${condition1}">
    ...
  </c:when>
  <c:when test="${condition2}">
    ...
  </c:when>
  <c:otherwise>
    ...
  </c:otherwise>
</c:choose>

#5 building

You must use the following code:

And <% @ taglib prefix = "C" URI = "http://www.springframework.org/tags/form"% >

and

<c:select>
            <option value="RCV"
                ${records[0].getDirection() == 'RCV' ? 'selected="true"' : ''}>
                <spring:message code="dropdown.Incoming" text="dropdown.Incoming" />
            </option>
            <option value="SND"
                ${records[0].getDirection() == 'SND'? 'selected="true"' : ''}>
                <spring:message code="dropdown.Outgoing" text="dropdown.Outgoing" />
            </option>
        </c:select>

Topics: Spring