Ternary operator in JSTL/EL

半城伤御伤魂 提交于 2019-11-26 16:20:40

问题


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"%>

回答1:


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}" />


来源:https://stackoverflow.com/questions/14482451/ternary-operator-in-jstl-el

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!