早期 JSP 混雜 Java 程式碼、JavaScript、HTML,維護困難。JSTL(JSP Standard Tag Library)與自定義標籤技術應運而生,將邏輯封裝於標籤處理類,JSP 頁面僅保留標籤調用,實現「邏輯與視圖分離」。
package com.example.tag;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.IOException;
public class HelloTag extends TagSupport {
@Override
public int doStartTag() throws JspException {
try {
pageContext.getOut().print("Hello World!");
} catch (IOException e) {
throw new JspException(e);
}
return SKIP_BODY; // 無標籤主體內容
}
}
關鍵常數:
EVAL_BODY_INCLUDE:處理標籤主體內容。SKIP_BODY:略過主體(無主體標籤)。EVAL_PAGE / SKIP_PAGE:控制頁面後續執行流程。路徑:WEB-INF/tlds/hello.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://java.sun.com/xml/ns/javaee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>hello</short-name>
<uri>https://example.com/hello</uri>
<tag>
<name>hello</name>
<tag-class>com.example.tag.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
<%@ taglib prefix="my" uri="https://example.com/hello" %>
<html>
<body>
<my:hello /><br/>
<my:hello />
</body>
</html>
輸出結果: 兩行 Hello World!
<my:pager total="${total}" pageSize="10" />。| 類型 | 繼承類別 | 適用場景 | 關鍵方法 |
|---|---|---|---|
| 簡單標籤 | TagSupport | 無主體、無屬性 | doStartTag / doEndTag |
| 帶屬性標籤 | TagSupport | 需動態參數 | setter/getter + doStartTag |
| 帶主體標籤 | BodyTagSupport | 需處理主體內容(迴圈、條件、轉換) | doAfterBody, doInitBody |
| SimpleTag (JSP 2.0+) | SimpleTagSupport | 更簡潔 API,取代 BodyTagSupport | doTag(), getJspBody().invoke() |
public class RepeatTag extends SimpleTagSupport {
private int count;
public void setCount(int count) { this.count = count; }
@Override
public void doTag() throws JspException, IOException {
JspFragment body = getJspBody();
for (int i = 0; i < count; i++) {
body.invoke(getJspContext().getOut()); // 輸出主體內容
}
}
}
TLD 定義 <attribute><name>count</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>。
JSP 使用:<my:repeat count="3"><li>項目</li></my:repeat>
WEB-INF/tlds/ 或 JAR 的 META-INF/,容器自動掃描。web.xml 可選配置 <jsp-config><taglib> 映射 URI。c、fmt、fn、my)。