Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between <c:if> and <c:when>?

Tags:

jsp

jstl

I've noticed usages of <c:if ...> in one place of JSP code and <c:when ...> in the other. The things they do look the same for me. Are these two commands just aliases?

like image 457
Dan Avatar asked Nov 26 '12 17:11

Dan


People also ask

Can we use c if inside c otherwise?

The < c:otherwise > is also subtag of < choose > it follows &l;twhen > tags and runs only if all the prior condition evaluated is 'false'. The c:when and c:otherwise works like if-else statement. But it must be placed inside c:choose tag.

What is the use of c if tag?

The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated is true. It is a simple conditional tag which is used for evaluating the body content, if the supplied condition is true.


2 Answers

<c:if is a simple if-clause. <c:when> has options for multiple if-clauses and an else clause. Compare:

<c:if test="${foo == 'bar'}">...</c:if> 

with

<c:choose>    <c:when test="${foo == 'bar'}">...</c:when>    <c:when test="${foo == 'baz'}">...</c:when>    <c:otherwise>...</c:otherwise> </c:choose> 
like image 200
Bozho Avatar answered Oct 14 '22 20:10

Bozho


<c:if> doesn't support any kind of "else" or "else if" functionality. <c:when> does. So if you need something analogous to

if (some_condition) {     // ... } 

then use <c:if>. If you need something analogous to

if (some_condition) {     // ... } else if (some_other_condition) {     // ... } else {     // ... } 

then use <c:choose> with <c:when> and (optionally) <c:otherwise>.

like image 21
Asaph Avatar answered Oct 14 '22 18:10

Asaph