The JSP JSTL Core <c:if>
tag is a conditional tag in the JSP Standard Tag Library (JSTL) core library. It includes a piece of content within the JSP page only if a specific condition is true
.
<c:if>
Tag Syntax
Syntax:
<c:if test="condition">
content to be included if the condition is true
</c:if>
<c:if>
Tag Attributes
The JSP JSTL Core <c:if>
tag has only one required attribute:
Attribute | Description |
---|---|
test | This attribute defines the condition that should be evaluated. The condition is an expression, which can be a Boolean expression or a value that can be converted to a Boolean. If the condition is true , the content within the <c:if> tag will be included in the JSP page; otherwise ignored.
|
<c:if>
Tag Example
Here is an example of how the JSP JSTL Core <c:if>
tag can be used within a JSP page:
Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Example of if in core-JSTL</title>
</head>
<body>
<c:set var="age" scope="request" value="${21}" />
<c:if test="${age >= 18}">
<p>You are an adult.</p>
</c:if>
<c:if test="${age < 18}">
<p>You are not an adult.</p>
</c:if>
</body>
</html>
Output:
You are an adult.
In this example, the JSTL core tag library is imported with the taglib
directive at the top of the page. The <c:if>
tag is then used to check if the value of the "age
" request parameter is greater than or equal to 18
. If the condition is true
, the message "You are an adult" will be displayed on the page. If the condition is false
, the message "You are not an adult" will be displayed on the page.
It is worth mentioning that you can use <c:choose>
, <c:when>
, and <c:otherwise>
tags in combination with <c:if>
to create more complex conditional statements.