Ternary operator in JSTL/EL
Asked Answered
J

1

45

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="http://java.sun.com/jsp/jstl/core"%>
Jo answered 23/1, 2013 at 14:48 Comment(4)
I copied and pasted your code and it works for me without error.Stepfather
@Stepfather - It might be the problem with the library version of JSTL I'm using. Which library are you using?Jo
The issue encountered here seems to be related to the EL parser, not to the JSTL. Which version of the Servlet API are you running your app on? 3.0 ? 2.5 ? Older ?Boccie
@Boccie - My Servlet version is 2.5.Jo
S
60

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

<%@taglib uri="http://java.sun.com/jsp/jstl/core" 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}" />
Stepfather answered 24/1, 2013 at 16:20 Comment(1)
I have recently downloaded NetBeans 7.2.1 and jdk 7 and reconfigured the whole application I'm working with all over again from scratch. NetBeans 7.2.1 has Apache Tomcat 7.0.27.0 (previously it was 6.0.26.0 with NetBeans 6.9.1) which supports Servlet 3.0 (previously it was 2.5) where the problem in question disappeared. I didn't change the JSTL library. It is still JSTL 1.1 as before.Jo

© 2022 - 2024 — McMap. All rights reserved.