JSP Standard Tag Library (JSTL) 提供標準化標籤實作常見 Web 功能,減少 JSP 中 Java 程式碼,利於前後端分工。
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="sql" uri="https://java.sun.com/jsp/jstl/sql" %> <%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
<c:out value="..." />:輸出表達式結果,等同 ${...},自動逃脫 XML 特殊字元。<c:set var="name" value="value" scope="session" />:設定範圍變數。<c:remove var="name" scope="session" />:移除範圍變數。<c:catch var="exception">...</c:catch>:捕獲例外,存入變數。<c:if test="${condition}">...</c:if>:單一條件。<c:choose><c:when test="...">...</c:when><c:otherwise>...</c:otherwise></c:choose>:多重互斥條件(如 if-else if-else)。<c:forEach items="${list}" var="item" varStatus="status">
${status.index} : ${item.name}
</c:forEach>
<c:forEach var="i" begin="1" end="10" step="2"> ${i} </c:forEach>
<c:forTokens items="a:b:c" delims=":" var="token"> ${token} </c:forTokens>
<c:import url="..." />:引入外部資源。<c:redirect url="..."><c:param name="k" value="v"/></c:redirect>:重導向並附帶參數。<c:url value="..." />:重寫 URL(含 Session ID)。<sql:setDataSource dataSource="jdbc/mydb" />
<sql:query var="users">SELECT * FROM users</sql:query>
<c:forEach items="${users.rows}" var="row">${row.name}</c:forEach>
<sql:update>UPDATE users SET name=? WHERE id=?<sql:param value="new"/><sql:param value="1"/></sql:update>
<fmt:formatNumber value="12.3" pattern="0.000" /> <!-- 12.300 -->
<fmt:formatDate value="${now}" type="date" /> <!-- 2024-01-15 -->
<fmt:formatDate value="${now}" type="time" /> <!-- 14:30:00 -->
<fmt:formatDate value="${now}" type="both" /> <!-- 2024-01-15 14:30:00 -->
${param.name} 替代 request.getParameter("name")。${paramValues.ids} 取得陣列參數。