<!--#include file="header.html" -->,需特定副檔名 .shtml、伺服器配置、動態內容支援有限、與 JSP 難共存。| 機制 | 語法 | 處理階段 | 適用場景 | 效能 |
|---|---|---|---|---|
| 靜態包含 (Include Directive) | <%@ include file="header.jsp" %> | 編譯期(JSP → Servlet 時) | 極少變更的靜態片段:Header、Footer、導航欄、CSS/JS 引用 | 最快,合併為單一 Servlet,零運行期開銷 |
| 動態包含 (Include Action) | <jsp:include page="fragment.jsp" flush="true" /> | 請求期(每次請求執行) | 頻繁變更、帶邏輯的動態片段:側邊欄、推薦列表、用戶面板 | 略低,獨立編譯執行,支援參數傳遞 |
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>網站標題</title>
<%@ include file="/common/head.jsp" %> <!-- CSS、JS、Meta -->
</head>
<body>
<%@ include file="/common/header.jsp" %> <!-- Logo、導航 -->
<%@ include file="/common/nav.jsp" %> <!-- 側邊選單 -->
<div id="content">
<!-- 主內容區,各頁面不同 -->
</div>
<%@ include file="/common/footer.jsp" %> <!-- 版權、連結 -->
</body></html>
關鍵點: 被包含檔案無需完整 HTML 結構,僅含片段標記。編譯後生成單一巨大 Servlet,執行效能最高。
<jsp:include page="/widgets/userPanel.jsp" flush="true">
<jsp:param name="userId" value="${param.id}" />
<jsp:param name="showDetail" value="true" />
</jsp:include>
<c:choose>
<c:when test="${user.role == 'admin'}">
<jsp:include page="/widgets/adminConsole.jsp" flush="true" />
</c:when>
<c:otherwise>
<jsp:include page="/widgets/userDashboard.jsp" flush="true" />
</c:otherwise>
</c:choose>
flush="true":包含前刷新輸出緩衝,確保順序正確。jsp:param:向被包含頁面傳遞額外參數,請求參數自動合併。<c:if>/<c:choose> 條件式包含。問題: 靜態包含指令會將被包含檔案內容在編譯期「內聯」至主頁面。若被包含檔案為動態內容(如資料庫查詢結果),主頁面重新編譯前不會反映最新資料。
驗證: 修改
included.html內容,重新整理主頁面,發現未更新。
<jsp:include>:每次請求重新執行被包含頁面。reloadable="true":Tomcat 自動偵測檔案變更重載(生產環境必須關閉)。<esi:include src="/fragment" />,在邊緣節點組裝頁面,動態片段獨立快取策略。<%@ taglib prefix="cache" uri="..." %><cache:cache key="sidebar" timeout="300">...</cache:cache> 區塊級快取。.jsp:增加每請求解析開銷。.shtml:破壞 JSP 標準行為。JSP Include 機制以「編譯期靜態包含」追求極致效能,「請求期動態包含」支援靈活組合。核心決策邏輯:片段內容是否每請求皆不同? 是 → 動態包含;否 → 靜態包含。現代架構下,配合片段化設計、區塊快取、邊緣組裝,可構建高效能、易維護的頁面佈局體系。