JSTL Tags Overview¶
1. <c:set> Tag¶
The <c:set> tag is used to set a variable or assign a value to an attribute in different scopes.
Syntax:¶
<c:set var="variableName" value="expression" scope="scope" />
var: The name of the variable to be set.value: The value or expression to assign.scope(optional): Can bepage,request,session, orapplication.
Example of <c:set>:¶
<!-- Setting a string value -->
<c:set var="greeting" value="Hello, World!" />
<!-- Setting the result of an expression -->
<c:set var="sum" value="${5 + 10}" />
<!-- Setting a session-scoped variable -->
<c:set var="user" value="John Doe" scope="session" />
2. <c:when> Tag¶
The <c:when> tag is used in combination with <c:choose> for conditional logic. It works like an if statement and allows you to check conditions.
Syntax:¶
<c:choose>
<c:when test="condition">
<!-- Code executed when the condition is true -->
</c:when>
<c:otherwise>
<!-- Code executed when no conditions are true -->
</c:otherwise>
</c:choose>
Example of <c:when>:¶
<c:choose>
<c:when test="${age < 18}">
<p>You are a minor.</p>
</c:when>
<c:when test="${age >= 18}">
<p>You are an adult.</p>
</c:when>
<c:otherwise>
<p>Age is unknown.</p>
</c:otherwise>
</c:choose>
3. <c:choose> Tag¶
The <c:choose> tag works like a switch statement, providing multiple conditions to check.
Example of <c:choose>:¶
<c:choose>
<c:when test="${user.role == 'admin'}">
<p>Welcome, admin!</p>
</c:when>
<c:when test="${user.role == 'guest'}">
<p>Welcome, guest!</p>
</c:when>
<c:otherwise>
<p>Access denied.</p>
</c:otherwise>
</c:choose>
4. <c:forEach> Tag¶
The <c:forEach> tag is used to iterate over collections or arrays.
Syntax:¶
<c:forEach var="item" items="collectionOrArray">
<!-- Code to execute for each item -->
</c:forEach>
Example of <c:forEach>:¶
<c:forEach var="item" items="${itemList}">
<p>${item.name}</p>
</c:forEach>
Conclusion¶
JSTL provides a set of powerful tags for common tasks such as iteration, conditionals, and data manipulation. These tags help simplify JSP development by reducing the need for Java code within JSP files.