<c:if>和<c:when>之间有什么区别?

Dan*_*Dan 32 jsp jstl

我已经注意到<c:if ...>JSP代码在一个地方的用法,而在另一个地方<c:when ...>.他们做的事情对我来说都是一样的.这两个命令只是别名吗?

Boz*_*zho 48

<c:if是一个简单的if子句.<c:when>有多个if子句和else子句的选项.相比:

<c:if test="${foo == 'bar'}">...</c:if>
Run Code Online (Sandbox Code Playgroud)

<c:choose>
   <c:when test="${foo == 'bar'}">...</c:when>
   <c:when test="${foo == 'baz'}">...</c:when>
   <c:otherwise>...</c:otherwise>
</c:choose>
Run Code Online (Sandbox Code Playgroud)


Asa*_*aph 27

<c:if>不支持任何类型的"else"或"else if"功能.<c:when>确实.所以,如果你需要类似的东西

if (some_condition) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后用<c:if>.如果你需要类似的东西

if (some_condition) {
    // ...
} else if (some_other_condition) {
    // ...
} else {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

然后使用<c:choose><c:when>和(任选地)<c:otherwise>.