JSTL/EL中的三元运算符 [英] Ternary operator in JSTL/EL
问题描述
以下JSTL标记可用于在请求范围内为变量设置值.
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"/>
我想有条件地检查设置的变量value
是否为空,并使用<c:when>...</c:when>
相应地显示结果,如下所示.
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,
"$ {空值?'无':值}"包含无效的表达式: javax.el.ELException:错误解析:$ {空值?'None':value}
"${empty value?'None':value}" contains invalid expression(s): javax.el.ELException: Error Parsing: ${empty value?'None':value}
那为什么会发生这种情况?
So why does this happen?
我正在使用JSTL 1.1
库,其中包含以下标记库,
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"%>
推荐答案
我在Tomcat 5.59, JSP 2.0和 JSTL 1.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}" />
这篇关于JSTL/EL中的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!