JSTL (JavaServer Pages Standard Tag Library) คือชุด custom tags มาตรฐานสำหรับ JSP ให้ฟังก์ชันพื้นฐานที่ใช้บ่อย: iteration, conditionals, XML manipulation, internationalization, SQL, และ framework สำหรับผสาน custom tags
คุณสมบัติหลัก
- Core:
<c:forEach>,<c:if>,<c:choose>,<c:set>,<c:out>,<c:url>ฯลฯ - Formatting: จัดรูปแบบตัวเลข, วันที่, เงิน, I18N
- SQL: query, update database โดยตรงใน JSP (ไม่แนะนำ production)
- XML: parse, transform, xpath
- Functions: string manipulation utilities
การติดตั้ง (Apache Tomcat)
- Step 1: ดาวน์โหลด binary distribution จาก Apache Standard Taglib แตกไฟล์
- Step 2: คัดลอก JAR files จากโฟลเดอร์ 'lib' ไป
webapps\ROOT\WEB-INF\lib\
การใช้งาน
ประกาศ taglib directive ที่ด้านบน JSP:
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="https://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
ตัวอย่าง: Loop และ Condition
<c:forEach var="i" begin="1" end="5">
Item <c:out value="${i}"/><br/>
</c:forEach>
<c:if test="${user.age >= 18}">
ผู้ใหญ่
</c:if>
ข้อดีของ JSTL
- ลด Java code ใน JSP (Scriptless JSP)
- มาตรฐาน Portable รันได้ทุก container
- Expression Language (EL) integration
- Auto-escaping ป้องกัน XSS
- อ่านง่าย ใกล้เคียง HTML