本文將詳細示範在 Orion Application Server 中開發自定義 JSP 標籤的完整流程:從標籤類別實作、TLD 描述檔編寫、JAR 封裝,到 JSP 頁面測試驗證。
package com.acme.mytags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloWorld implements Tag {
private PageContext pageContext;
private Tag parent;
// 標籤開始處理
public int doStartTag() throws JspException {
return SKIP_BODY; // 標籤無內容主體
}
// 標籤結束處理:輸出內容
public int doEndTag() throws JspException {
try {
pageContext.getOut().write("Hello World!");
} catch (java.io.IOException e) {
throw new JspException("IO Error: " + e.getMessage());
}
return EVAL_PAGE;
}
// 生命週期方法
public void release() {}
public void setPageContext(PageContext pc) { this.pageContext = pc; }
public void setParent(Tag parent) { this.parent = parent; }
public Tag getParent() { return parent; }
}
建立 taglib.tld(XML 格式):
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"https://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>mt</shortname>
<uri>https://www.orionserver.com/tutorials/tagtut/lesson1/mytags.jar</uri>
<info>My first Tag library</info>
<tag>
<name>helloWorld</name>
<tagclass>com.acme.mytags.HelloWorld</tagclass>
<bodycontent>empty</bodycontent>
<info>A Hello world Tag</info>
</tag>
</taglib>
目錄結構:
mytags.jar
├── com/acme/mytags/HelloWorld.class
└── META-INF/taglib.tld
<%@ taglib uri="https://www.orionserver.com/tutorials/tagtut/lesson1/mytags.jar" prefix="my" %>
<html><body>
<my:helloWorld />
</body></html>
default-web-app/tag/mytags.jar 與 hello.jsp 放入該目錄https://localhost:[port]/tag/hello.jsp下載:完整範例檔案