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

ตัวอย่างการใช้งานคำสั่ง taglib directive ใน JSP

คำสั่ง taglib directive ประกาศว่า JSP หน้านี้ใช้ custom tag library ระบุตำแหน่งไลบรารี และ prefix สำหรับเรียกใช้ tag

รูปแบบภาษา JSP

<%@ taglib uri="uri" prefix="prefixOfTag" %>

รูปแบบ XML

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
  • uri - ตำแหน่งของ tag library (path ไฟล์ .tld หรือ URN)
  • prefix - คำนำหน้าสำหรับ tag (เช่น c, fmt, ex)

ตัวอย่างการใช้งาน

สมมติ tag library ชื่อ custlib มี tag ชื่อ hello ใช้ prefix mytag:

<%@ taglib uri="https://www.example.com/custlib" prefix="mytag" %>
<html>
<body>
    <mytag:hello/>
</body>
</html>

ตัวอย่างจริงกับ JSTL Core

<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
    <c:out value="สวัสดี JSTL!"/>
</body>
</html>

จุดสำคัญ

  • ต้องมีไฟล์ .tld อยู่ใน WEB-INF/ หรือใน JAR ภายใต้ WEB-INF/lib/
  • uri ใน taglib directive ต้องตรงกับ <uri> ในไฟล์ .tld หรือเป็น path ไปยังไฟล์ .tld
  • prefix ควรสั้นและมีความหมาย (c, fmt, fn, ex, mytags ฯลฯ)