專案中發現 `.tag` 檔案,原以為是第三方模板引擎,查證後才知是 JSP 2.0 引入的 Tag File 與 JSP Fragment 技術。比傳統 `
WEB-INF/tags/tpl.tag<%@ tag language="java" pageEncoding="UTF-8"%>
<%@ attribute name="title"%>
<%@ attribute name="tpl1" fragment="true" required="true"%>
<%@ attribute name="tpl2" fragment="true" required="true"%>
<%@ attribute name="tpl3" fragment="true" required="true"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>${title}</title>
<style>
#div1,#div2,#div3 { width:90%; margin:10px auto; border:10px solid red; }
</style>
</head>
<body>
<h1>jsp2.0 標籤檔案</h1>
<div id="div1"><jsp:invoke fragment="tpl1" /></div>
<div id="div2"><jsp:invoke fragment="tpl2" /></div>
<div id="div3"><jsp:invoke fragment="tpl3" /></div>
<h2>jsp2.0 fragment 技術</h2>
</body>
</html>
index.jsp<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="xjo" tagdir="/WEB-INF/tags" %>
<xjo:tpl title="jsp標籤檔案的使用">
<jsp:attribute name="tpl1">
<h1>tpl1 中的內容</h1>
</jsp:attribute>
<jsp:attribute name="tpl2">
<h1>tpl2 中的內容</h1>
</jsp:attribute>
<jsp:attribute name="tpl3">
<h1>tpl3 中的內容</h1>
</jsp:attribute>
</xjo:tpl>
| 特性 | 傳統 include | Tag File + Fragment |
|---|---|---|
| 參數傳遞 | 僅請求參數/屬性 | 支援 Fragment 內容塊延遲渲染 |
| 結構控制 | 被包含頁面決定結構 | 模板標籤完全掌控佈局結構 |
| 類型安全 | 無 | 屬性可宣告 required、type、fragment |
| IDE 支援 | 弱 | Eclipse/MyEclipse 可識別 .tag 提供自動完成 |
Tag File + Fragment 是 JSP 原生的「模板繼承」實現,無需引入 SiteMesh、Tiles、Freemarker 等第三方框架,輕量且標準化,強烈建議在 JSP 2.0+ 環境優先採用。