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

วิธีลบตัวแปร Java จาก Scope ใน JSP ด้วย <c:remove>

Tag <c:remove> ลบ variable จาก scope ที่ระบุ หรือ scope แรกที่พบ (ถ้าไม่ระบุ scope)

Attributes

AttributeคำอธิบายRequiredDefault
varชื่อ variable ที่จะลบYes-
scopeScope: page, request, session, applicationNoAll scopes

ตัวอย่าง

<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<html>
<body>
    <c:set var="salary" scope="session" value="${2000 * 2}"/>
    <p>Before Remove: <c:out value="${salary}"/></p>
    
    <c:remove var="salary"/>  <!-- ลบจากทุก scope -->
    
    <p>After Remove: <c:out value="${salary}"/></p>
</body>
</html>

ผลลัพธ์

Before Remove: 4000
After Remove: 

(After Remove แสดงว่าง เพราะ variable ถูกลบแล้ว EL คืน empty string)

การระบุ Scope

<c:remove var="tempData" scope="request"/>   <-- ลบแค่ request scope -->
<c:remove var="userPrefs" scope="session"/> <-- ลบแค่ session scope -->
<c:remove var="appConfig" scope="application"/> <-- ลบแค่ application scope -->

กรณีการใช้งาน

  • Cleanup temporary variables หลังใช้งาน
  • Logout: ลบ session attributes เฉพาะตัว
  • Multi-step wizard: ลบ step data เก่า
  • Prevent memory leaks ใน long-running sessions

ข้อสังเกต

  • ไม่ error ถ้า variable ไม่มีอยู่ (silent)
  • ลบจาก scope แรกที่พบตามลำดับ: page → request → session → application
  • ไม่ลบ attribute ของ Java objects อื่นๆ ที่อาจ reference อยู่
  • ใช้ร่วมกับ <c:set> จัดการ lifecycle ของ scoped variables