if statement - if...else within JSP or JSTL

ID : 10144

viewed : 28

Tags : jspif-statementjstljsp

Top 5 Answer for if statement - if...else within JSP or JSTL

vote vote

95

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> 
vote vote

85

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.

vote vote

70

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.

vote vote

64

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> 
vote vote

60

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %> <c:set var="val" value="5"/> <c:choose>    <c:when test="${val == '5'}">     Value is 5   </c:when>   <c:otherwise>     Value is not 5   </c:otherwise> </c:choose> 

Top 3 video Explaining if statement - if...else within JSP or JSTL

Related QUESTION?