JSTL Core Tag c:if Example
- Details
- Written by Nam Ha Minh
- Last Updated on 31 August 2019   |   Print Email
JSTL <c:if> Syntax
<c:if test="<boolean>" var="<string>" scope="<string>">...
</c:if>Attributes
Name | Required | Type | Description |
test | True | boolean | Test expression which determines whether body content is executed or not. If test evaluates to true body content is executed. |
var | False | java.lang.String | Name of the variable which holds the result of the test condition. The type of this variable is Boolean. |
scope | False | java.lang.String | Scope of the var |
JSTL <c:if> Example:
The below is an example which takes radio button selection from user and displays message whether user likes movies or not. Note that there is no ‘else’ construct.<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title><c:if> Demo</title> </head> <body> <h1><c:if> Demo</h1> <c:if test="${param.movieCheck == 'yes'}"> Ok! Great Choice! </c:if> <c:if test="${param.movieCheck == 'no'}"> Oops! Perhaps you can try watching them! </c:if> <br/> <br/> <form name="ifForm" action="${pageContext.request.contextPath}/tag-types/core/if.jsp" method="POST"> Do you like movies? <br/> Yes <input type="radio" name="movieCheck" value="yes"/><br/> No <input type="radio" name="movieCheck" value="no"/><br/> <input type="submit" value="submit"/> </form> </body> </html>The below example checks the value of a variable age, if the given age is more than 18 it is printing a message. Note that the variable booleanValue holds the actual result of the test expression in this case evaluates to true.
<c:set var="age" scope="session" value="20"/> <c:if test="${age > 18}" var="booleanValue"> <p>Eligible to vote because you're <c:out value="${age}"/> years old.</p> <p>Test result is <c:out value="${booleanValue}"/></p> </c:if>The below example retrieves the logged in user information from request scope, if the user is admin displaying a message.
<c:if test="${loggedInUser==’admin’}"> Ok you’re administrator! </c:if>Note that there is no ‘else’ part of the condition. For more sophisticated ‘if-else’ scenario we use tags <c:choose>, <c:when> and <c:otherwise>.
Output:
In the above screen, we are using <C:if>to display a message based on the choice selected by the user.Recommended Usage of JSTL <c:if> tag:
Particularly useful if we have only one condition to evaluate and we do not need to evaluate else conditions.Other JSTL Core Tags:
catch | choose | forEach | forTokens | import | out | param | redirect | remove | set | url
Comments
When the value of test expression of c:if tag changes dynamically, its contents are being appended at the end of the tree. Why does this happen?