Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

การใช้งาน <c:choose> tag ใน JSP

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> เมื่อมีหลายเงื่อนไข mutually exclusive, ใช้ <c:if> สำหรับเงื่อนไขเดี่ยวหรือ independent conditions

คุณสมบัติ<c:choose><c:if>
Multiple conditionsรองรับ (หลาย when)ไม่รองรับ (ต้อง nested if)
Mutually exclusiveใช่ (เลือก 1 กรณี)ไม่ (if หลายตัว true ได้)
Default case<c:otherwise>ไม่มี
Performanceหยุดเมื่อเจอ trueeval ทุก if