Tag <c:choose> ทำงานแบบ switch-case ใน Java มี <c:when> (case) และ <c:otherwise> (default)
โครงสร้าง
<c:choose>
<c:when test="${condition1}">...</c:when>
<c:when test="${condition2}">...</c:when>
<c:otherwise>...</c:otherwise>
</c:choose>
Attributes
<c:choose>- ไม่มี attribute<c:when>- test (required) - EL expression boolean<c:otherwise>- ไม่มี attribute
ตัวอย่าง: เกรดเงินเดือน
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:set var="salary" scope="session" value="${2000 * 2}"/>
<p>Your salary: <c:out value="${salary}"/></p>
<c:choose>
<c:when test="${salary <= 0}">
Salary is very low.
</c:when>
<c:when test="${salary > 1000}">
Salary is very good.
</c:when>
<c:otherwise>
No comment.
</c:otherwise>
</c:choose>
</body>
</html>
ผลลัพธ์
Your salary: 4000 Salary is very good.
จุดสำคัญ
- เงื่อนไขใน
testใช้ EL expressions (SpEL syntax) - Evaluates แบบ top-down หา
<c:when>แรกที่ true แล้วจบ (ไม่ fall-through) <c:otherwise>ต้องอยู่ท้ายสุด (optional)- สามารถ nested ได้
เปรียบเทียบ <c:choose> vs <c:if>
| คุณสมบัติ | <c:choose> | <c:if> |
|---|---|---|
| Multiple conditions | รองรับ (หลาย when) | ไม่รองรับ (ต้อง nested if) |
| Mutually exclusive | ใช่ (เลือก 1 กรณี) | ไม่ (if หลายตัว true ได้) |
| Default case | <c:otherwise> | ไม่มี |
| Performance | หยุดเมื่อเจอ true | eval ทุก if |