if...else within JSP or JSTL
The construct for this is:
<c:choose>
<c:when test="${..}">...</c:when> <!-- if condition -->
<c:when test="${..}">...</c:when> <!-- else if condition -->
<c:otherwise>...</c:otherwise> <!-- else condition -->
</c:choose>
If the condition isn't expensive, I sometimes prefer to simply use two distinct <c:if
tags - it makes it easier to read.
Should I use JSTL ?
Yes.
You can use <c:if>
and <c:choose>
tags to make conditional rendering in jsp using JSTL.
To simulate if , you can use:
<c:if test="condition"></c:if>
To simulate if...else, you can use:
<c:choose>
<c:when test="${param.enter=='1'}">
pizza.
<br />
</c:when>
<c:otherwise>
pizzas.
<br />
</c:otherwise>
</c:choose>
In case you want to compare strings, write the following JSTL:
<c:choose>
<c:when test="${myvar.equals('foo')}">
...
</c:when>
<c:when test="${myvar.equals('bar')}">
...
</c:when>
<c:otherwise>
...
</c:otherwise>
</c:choose>
If you just want to output different text, a more concise example would be
${condition ? 'some text when true' : 'some text when false'}
It is way shorter than c:choose.