There is no if-else, just if.
<c:if test="${user.age ge 40}">
You are over the hill.
</c:if>
Optionally you can 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>
In addition with skaffman answer, simple if-else you can use ternary operator like this
<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>
I got away with simply using two if tags, thought I'd add an answer in case it's of use to anyone else:
<c:if test="${condition}">
...
</c:if>
<c:if test="${!condition}">
...
</c:if>
whilst technically not an if-else
per se, the behaviour is the same and avoids the clunky approach of using the choose
tag, so depending on how complex your requirement is this might be preferable.
This is good and efficient approach as per time complexity prospect. Once it will get a true condition , it will not check any other after this. In multiple If , it will check each and condition.
<c:choose>
<c:when test="${condtion1}">
do something condtion1
</c:when>
<c:when test="${condtion2}">
do something condtion2
</c:when>
......
......
......
.......
<c:when test="${condtionN}">
do something condtionn N
</c:when>
<c:otherwise>
do this w
</c:otherwise>
</c:choose>
Besides the need to have an else, in many cases you will need to use the same condition on multiple locations.
I prefer to extract the condition into a variable:
<c:set var="conditionVar" value="#{expression}"/>
And after that, you can use the condition variable as many times as you need it:
...
<c:if test="#{conditionVar}">
...
</c:if>
<c:if test="#{!conditionVar}">
...
</c:if>
...
<c:if test="#{conditionVar}">
...
</c:if>
<c:if test="#{!conditionVar}">
...
</c:if>
...
The c:choose element is good for more complicated situations, but if you need an if else only, I think this approach is better. It is efficient and has the following benefits:
you have to use this code:
with <%@ 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>
Source: Stackoverflow.com