automatically written to the output stream. The JSTL tags <c:if> and <c:choose> make it possible to dynamically generate template text depending on a condition.
<c:if >
The <c:if> tag generates its body if the expression in the test attribute evaluates to the boolean value true or the string value"true">:
<%-- Declare the core library --%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%-- Simple if conditions --%> <c:if test='${param.p == "someValue"}'> Generate this template text if p equals someValue </c:if> <c:if test='${param.p}'> Generate this template text if p equals "true" </c:if>
<c:choose > , <c:when > and, <c:otherwise >
This tags are used to write code in the form of if/else , if / elseif / else ...
Check the bellow example for how we can achieve if/else code using choose / when / otherwise in JSTL
<%-- A simple if/else condition --%> <c:choose> <c:when test='${param.p == "someValue"}'> Generate this template text if p equals someValue </c:when> <c:otherwise> Otherwise generate this template text </c:otherwise> </c:choose>
If you want to use nested if / elseif / else ... condition then check the following sample code
<c:choose> <c:when test='${param.p == "0"}'> Generate this template text if p equals 0 </c:when> <c:when test='${param.p == "1"}'> Generate this template text if p equals 1 </c:when> <c:otherwise> Generate this template text if p equals anything else </c:otherwise> </c:choose>
The <c:out> can also be used to conditionally generate template text. If the value attribute is null, a default value (if specified) is generated. The default value can be specified using the default attribute or can be specified in the body content. This example demonstrates both methods:
<%-- Default value in an attribute --%> <%-- Default value in the body content --%> <c:out value='${param.p}'> Generate this if p is null </c:out>
No comments:
Post a Comment