Menu

Showing posts with label JSTL. Show all posts
Showing posts with label JSTL. Show all posts

If else || nested if statement in JSTL

Today we will discuss about; how to write simple if else and nested if else statements in JSTL.

If you have to check only a single value then you can use if statement "<c:if>" in JSTL. But if you want to achieve nested if else then you have to use <c:when> and <c:otherwise>.

Will will see both if and nested if else in JSTL with an example.

To use the JSTL in your JSP file we have to first import the JSTL tag library in our JSP file. Below is the import statement to where we are importing JSTL core tag library in our JSP. Specify a prefix to this tag which we will prefix further with our tag.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
prefix="c" use c when you use JSTL tags in your JSP file.
e.g. <c:if>, <c:choose>

Suppose we have a variable name which have a name of an user. let see how will check this using if statement in jstl.
Using <c:set> tag we can declare and set value to a variable. In below statement we are declaring a variable name and assigning its value RASHID.
<c:set var=name value="RASHID">
Now see the if condition 
 <c:if test="${name == 'RASHID'}">
 <c:set var=age value=23 />
</c:if>
Now we will using nested if else how will check the value of variable name in jstl.
<c:choose>
         <c:when test = "${name == 'RASHID'}">
            HIS NAME IS RASHID.
         </c:when>
         <c:when test = "${name == 'Ranjan'}">
            HIS NAME IS Ranjan.
         </c:when>
         <c:otherwise>
            No machtes....
         </c:otherwise>
 </c:choose>
Hope this will help you to understand the if else and nested if else condition using JSTL. Do let me know if you have any question and suggestions.