In this article we are discussing <c:choose>, <c:when> and <c:otherwise> core tags of JSTL. These tags are used together like switch-case and default statements in java. <c:choose> is the one which acts like switch, <c:when> like case which can be used multiple times inside <c:choose> for evaluating different-2 conditions. <c:otherwise> is similar to default statement which works when all the <c:when> statements holds false.
Syntax:
The basic structure looks like this –
<c:choose> <c:when test="${condition1}"> //do something if condition1 is true </c:when> <c:when test="${condition2}"> //do something if condition2 is true </c:when> <c:otherwise> //Statements which gets executed when all <c:when> tests are false. </c:otherwise> </c:choose>
Example
In this example we have three numbers and we are comparing them using these three core tags. Example is pretty simple to understand. Screenshot of output is provided after the example’s code.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>c:choose, c:when and c:otherwise Tag Example</title> </head> <body> <c:set var="number1" value="${222}"/> <c:set var="number2" value="${12}"/> <c:set var="number3" value="${10}"/> <c:choose> <c:when test="${number1 < number2}"> ${"number1 is less than number2"} </c:when> <c:when test="${number1 <= number3}"> ${"number1 is less than equal to number2"} </c:when> <c:otherwise> ${"number1 is largest number!"} </c:otherwise> </c:choose> </body> </html>
Output
Leave a Reply