| 術語 | 說明 |
|---|---|
| 標簽 | XML 元素,如 ` |
| 標簽庫 | 功能相關標簽的集合,如 JSTL、自定義業務標簽庫 |
| TLD 文件 | Tag Library Descriptor,XML 配置,定義標簽與處理類映射 |
| 標簽處理類 | 實現標簽邏輯的 Java 類,繼承 `TagSupport` 或實現 `SimpleTag` |
public class HelloTag extends TagSupport {
private String name; // 屬性對應 setter
public void setName(String name) { this.name = name; }
@Override
public int doStartTag() throws JspException {
try {
pageContext.getOut().print("Hello, " + name + "!");
} catch (IOException e) {
throw new JspException(e);
}
return SKIP_BODY; // 無標簽體
}
@Override
public int doEndTag() throws JspException {
return EVAL_PAGE; // 繼續執行頁面
}
}
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="https://java.sun.com/xml/ns/javaee" version="2.1">
<tlib-version>1.0</tlib-version>
<short-name>my</short-name>
<uri>https://example.com/mytags</uri>
<tag>
<name>hello</name>
<tag-class>com.example.tags.HelloTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
<jsp-config>
<taglib>
<taglib-uri>https://example.com/mytags</taglib-uri>
<taglib-location>/WEB-INF/mytags.tld</taglib-location>
</taglib>
</jsp-config>
<%@ taglib prefix="my" uri="https://example.com/mytags" %>
<my:hello name="${user.name}"/>
pageContext:容器在 `doStartTag` 前調用 `setPageContext` 注入,可訪問 request、session、application、out 等隱含對象。parent:巢狀標簽時指向父標簽處理類,支持協作。更簡潔,無 `doStartTag/doEndTag`,只需實現 `doTag()`,通過 `getJspBody().invoke(null)` 處理標簽體,適合現代開發。