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

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

Tag <c:if> evaluate condition แสดง body เฉพาะเมื่อ true

Attributes

AttributeคำอธิบายRequiredDefault
testEL expression boolean conditionYes-
varVariable name เก็บผลลัพธ์ booleanNo-
scopeScope ของ var (page/request/session/application)Nopage

ตัวอย่างพื้นฐาน

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<html>
<body>
    <c:set var="salary" value="${2000 * 2}"/>
    
    <c:if test="${salary > 2000}">
        <p>My salary is: <c:out value="${salary}"/></p>
    </c:if>
</body>
</html>

ผลลัพธ์

My salary is: 4000

ตัวอย่างเก็บผลลัพธ์ใน Variable

<c:if test="${user.age >= 18}" var="isAdult" scope="request">
    <p>Adult content</p>
</c:if>
<c:if test="${isAdult}">
    <p>Show adult section</p>
</c:if>

ตัวอย่าง Else Logic (ใช้ 2 c:if)

<c:if test="${score >= 50}">Pass</c:if>
<c:if test="${score < 50}">Fail</c:if>

ข้อจำกัด

  • ไม่มี else/else-if ต้องใช้ <c:choose> แทน
  • ไม่รองรับ elseif ต้อง nested หรือใช้ choose
  • Body content แสดงเฉพาะ test=true

Best Practices

    1. ใช้ <c:choose> เมื่อมี multiple mutually exclusive conditions 2. ใช้ var + scope เพื่อ reuse condition result 3. EL expressions ควร simple ไม่ควร logic ซับซ้อนใน JSP 4. Escape output ด้วย <c:out> ภายใน if body