JSTL 中是否有可用的 if-else 标签?
是的,但它很笨重,例如
<c:choose>
<c:when test="${condition1}">
...
</c:when>
<c:when test="${condition2}">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>
除了 skaffman 的回答,简单的 if-else 你可以像这样使用三元运算符
<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>
没有if-else,只是如果。
<c:if test="${user.age ge 40}">
You are over the hill.
</c:if>
或者,您可以使用选择时间:
<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>
我只是使用了两个 if 标签就逃脱了,我想我会添加一个答案,以防它对其他人有用:
<c:if test="${condition}">
...
</c:if>
<c:if test="${!condition}">
...
</c:if>
虽然技术上不是 if-else
本身,但行为是相同的,并且避免了使用 choose
标记的笨拙方法,因此根据您的要求有多复杂,这可能是更可取的。
choose
标记。
你必须使用这个代码:
与<%@ taglib prefix="c" uri="http://www.springframework.org/tags/form"%>
和
<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>
除了需要 else 之外,在许多情况下,您还需要在多个位置使用相同的条件。
我更喜欢将条件提取到变量中:
<c:set var="conditionVar" value="#{expression}"/>
之后,您可以根据需要多次使用条件变量:
...
<c:if test="#{conditionVar}">
...
</c:if>
<c:if test="#{!conditionVar}">
...
</c:if>
...
<c:if test="#{conditionVar}">
...
</c:if>
<c:if test="#{!conditionVar}">
...
</c:if>
...
c:choose 元素适用于更复杂的情况,但如果您只需要 if else,我认为这种方法更好。它是高效的并且具有以下优点:
如果变量名选择得当,则更具可读性
更可重用,因为条件被提取并且结果变量可以重用于其他 if 和其他表达式。它不鼓励多次编写相同的条件(并对其进行评估)。
根据时间复杂度的前景,这是一种很好且有效的方法。一旦它得到一个真实的条件,它就不会在此之后检查任何其他的。在多个 If 中,它将检查每个 and 条件。
<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>
<c:otherwise>
似乎有点冗长,是吗?