jstl if else

Here we have given a simple example to explain the implementation of if-else tag in JSTL.

jstl if else

In this section we have discussed about how to implement if-else tag in JSTL using a simple example.

<c:if> tag does not work if the value entered does not match with any of the condition given in the program, as their is not default value.

Hence, if-else tag is not implemented directly but is implemented with the help of some tags:

<c:choose> tag : works like if-else statement in a java programming. It performs conditional operations using <when> and <otherwise>.

<c:when> tag is a sub tag of <c:choose> and provides boolean expression to evaluate. If it is true rest of the body is evaluated.

<c:otherwise> tag is a sub tag of <c:choose> and is evaluated when condition provided to the <c:when> tag is false.

For this program to work, one must have jstl.jar and standard.jar in /WEB-INF/lib folder.

Example:

<html>
<head>
<title>How to Use Choose,Otherwise and When</title>
</head>

<body bgcolor = "#FFFFCC">
<form method="get">Enter a number from one onwards :
<input type="text" name="number" /><br>
<input type="submit" value="Submit" />
</form>

<c:if test="${pageContext.request.method=='GET'}">So, you want only
<c:out value="${param.number}" />

<c:choose>
<c:when test="${param.number=='1'}">banana.

</c:when>

<c:otherwise>bananas.

</c:otherwise>
</c:choose>
</c:if>
</body>
</html>

Resource: