<c:if> is a JSTL core tag which is used for testing conditions. It is more or like a if statement in java which evaluates a condition and executes a block of code if the result is true.
Syntax:
This is the basic syntax of <c:if> core tag. The set of statements enclosed within <c:if> tag gets executed if test=”true”. For using this tag we generally use expression language to evaluate an relational expression. We use EL because it returns boolean value(true/false) after evaluating the condition and we need the boolean value for test attribute.
<c:if test="${condition}"> ... .. </c:if>
Example of <c:if> tag
In this example we have defined age variable using <c:set> tag and then we are checking the eligibility of voting by using <c:if> tag.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <title>JSTL c:if Tag Example</title> </head> <body> <c:set var="age" value="26"/> <c:if test="${age >= 18}"> <c:out value="You are eligible for voting!"/> </c:if> <c:if test="${age < 18}"> <c:out value="You are not eligible for voting!"/> </c:if> </body> </html>
Output:
<c:if> attributes
Above we have seen the basic usage of <c:if> where we have used only the test attribute. However there are two other optional attributes for this tag which are var and scope. Using these attributes you can simply store the test results in a variable within a specified scope.
- var: Variable name in which the test result would be stored.
- scope: It defines the scope for storing the value. For e.g. if its session the stored var value can be accessed till the session is active.
An example of var and scope attribute
Storing the test result in variable res in request scope. For printing the value we have given requestScope.res as the variable is stored in request however you can even give variable name(res) alone, it would work fine.
<c:if test="${17 >= 18}" var="res" scope="request"> </c:if> <c:out value="${requestScope.res}"/>
sahul says
This is really very good site for learning jstl for beginners
keyur says
good site for learning jstl..
Nilesh Dhande says
Really, this is very useful explanation and thanks…
seema says
good site for learning jstl