Ternary Operator in Jstl/El

The following tag of JSTL can be used to set a value to a variable in a request scope.

<c:set var="value" scope="request" value="someValue"/>

I want to check conditionally, if the variable value being set is empty or not and display the result accordingly something like the following, using <c:when>...</c:when>.

<c:choose>
    <c:when test="${not empty value}">
        <c:out default="None" value="${value}"/>
    </c:when>
    <c:otherwise>
        <c:out default="None" value="None"/>
    </c:otherwise>
</c:choose>

I want to reduce the line of code using a ternary expression like,

<c:out default="None" value="${not empty value ? value : 'None'}"/>

It is evaluated as it actually means but if I interchange the order of the expressions like,

<c:out default="None" value="${empty value ? 'None' : value}"/>

then it is a syntax error indicating,

"${empty value?'None':value}" contains invalid expression(s): javax.el.ELException: Error Parsing: ${empty value?'None':value}

So why does this happen?


I'm using the JSTL 1.1 library and the following taglib is included,

<%@taglib prefix="c" uri=""%>
4

1 Answer

I tested the following page in Tomcat 5.59, JSP 2.0 and JSTL 1.1. It ran without any errors.

<%@taglib uri="" prefix="c"%> 
<c:set var="value" scope="request" value="someValue"/>
<c:out default="None" escapeXml="true" value="${not empty value ? value : 'None'}" />
<c:out default="None" escapeXml="true" value="${empty value ? 'None' : value}" />
<c:set var="value" scope="request" value="" />
<br/>
<c:out default="None" escapeXml="true" value="${not empty value ? value : 'None'}" />
<c:out default="None" escapeXml="true" value="${empty value ? 'None' : value}" />
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest