JSP If else condition using JSTL if and choose tags

We can use JSTL tags in JSP pages to evaluate if…else scenarios.
– c:if
– c:choose
 

JSTL Core “if” Tag

 
The “if” tag evaluates an expression and displays its body content only if the expression evaluates to true.
 

Attributes of if tag:

The if tag has following attributes:

Required attribute
test – This represents the condition to evaluate and is mandatory attribute.

Optional attribute
var – This is the aame of the variable to store the condition’s result.
scope – Scope of the variable to store the condition’s result.
 

Example:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:if> Tag Example</title>
</head>
<body>
<c:set var="quantity" scope="session" value="100"/>
<c:if test="${quantity > 0}">
   <p>Quanity available is: <c:out value="${quantity}"/><p>
</c:if>
</body>
</html>

 

Output

 
This would produce following result:

Quanity available is: 100
 

Disadvantage:

 
There is no else in JSTL. So for if..else scenarios, you have to do multiple if tags or you can use JSTL choose tag.

 

JSTL Core “choose” Tag

 
The “choose” tag works like a Java switch statement in that it lets you choose between a number of alternatives. While the switch statement has case statements, the choose tag has when tags. A a switch statement has default clause to specify a default action and similar way choose has otherwise as default clause.
 

Attribute:

The choose tag does not have any attribute.

The when tag has one attribute “test” which represents the condition to evaluate.

The otherwise tag does not have any attribute.

 

Example

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:choose> Tag Example</title>
</head>
<body>
<c:set var="quantity" scope="session" value="0"/>
<c:choose>
  <c:when test="${accessoryDetail.storeQuantity} gt 0">
    <p>${quantity} Available</p>
  </c:when>
  <c:otherwise>
    <p>Not available</p>
  </c:otherwise>
</c:choose>
</body>
</html>

 

Output

 
This would produce following result:

Not available
 

© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

You may also like...

Leave a Reply.. code can be added in <code> </code> tags