| 指令 | 用途 | 執行階段 |
|---|---|---|
page | 設定 JSP 頁面屬性 (編碼、繼承、匯入、錯誤頁等) | 編譯期 |
include | 靜態包含檔案內容 (編譯期合併) | 編譯期 |
taglib | 引入標籤庫 | 編譯期 |
<%@ page
language="java" <!-- 預設 java,理論支援其他腳本語言 -->
extends="com.example.BaseServlet" <!-- 生成 Servlet 繼承的父類 -->
import="java.util.*,java.sql.*" <!-- 匯入套件,可多次使用 -->
session="true" <!-- 是否自動建立 HttpSession -->
buffer="8kb" <!-- 輸出緩衝區大小,none 關閉 -->
autoFlush="true" <!-- 緩衝區滿時自動 flush -->
isThreadSafe="true" <!-- 是否支援多執行緒,false 則單執行緒模型 -->
info="版本 1.0" <!-- 存入 Servlet getServletInfo() -->
errorPage="/error.jsp" <!-- 發生未捕獲異常時轉向的錯誤頁 -->
contentType="text/html;charset=UTF-8" <-- 回應 Content-Type -->
isErrorPage="false" <!-- 是否為錯誤處理頁 (可用 exception 物件) -->
pageEncoding="UTF-8" <-- JSP 檔案儲存編碼 (優先於 contentType charset) -->
%>
pageEncoding:決定 **JSP 原始檔以何種編碼讀取/儲存**。編譯時將原始碼按此編碼解碼為 Unicode。contentType="text/html; charset=UTF-8":決定 **HTTP 回應標頭** `Content-Type: text/html; charset=UTF-8`,告訴瀏覽器以 UTF-8 解碼回應體。<!-- 一般頁面 -->
<%@ page errorPage="/error/500.jsp" %>
<!-- 錯誤頁面 error/500.jsp -->
<%@ page isErrorPage="true" %>
<%-- 此頁面可直接使用 exception 隱含物件 --%>
<h1>系統錯誤</h1>
<pre><%= exception.getMessage() %></pre>
buffer="none":直接輸出,forward 前不可有輸出buffer="16kb" + autoFlush="false":大頁面可減少網路交互,但 forward 前需手動 out.flush()<%@ include file="/common/header.jsp" %>
<!-- main.jsp -->
<%@ include file="fragment.jsp" %>
<% String path = request.getContextPath(); %>
<!-- fragment.jsp -->
<% String path = request.getContextPath(); %> <!-- 編譯錯誤:Duplicate local variable path -->
解決方案:
String fragPath = ...request.setAttribute("path", ...)<jsp:include page="..." /> (編譯為獨立 Servlet,變數隔離)| 特性 | <%@ include %> (靜態) | <jsp:include /> (動態) |
|---|---|---|
| 包含時機 | 編譯期 | 請求執行期 |
| 產出 Servlet | 單一 Servlet | 多個 Servlet |
| 變數作用域 | 共享 (易衝突) | 隔離 |
| 目標檔案變更 | 主頁面重新編譯 | 即時生效 |
| 可包含動態內容 | 是 (合併後執行) | 是 (獨立執行) |
| 效能 | 最佳 | 略低 (請求轉發) |
| 傳遞參數 | 不可 (共享 request) | <jsp:param> |
<%@ include file="/layout/header.jsp" %>,片段**不宣告區域變數**<jsp:include page="/module/userCard.jsp"><jsp:param name="userId" value="123"/></jsp:include>errorPage,錯誤頁設定 isErrorPage="true"pageEncoding="UTF-8" + contentType="text/html;charset=UTF-8"page 指令控制頁面編譯與執行行為,核心在編碼、錯誤處理、緩衝區設定。include 指令提供編譯期靜態包含,效能最佳但需注意變數衝突。現代開發中,佈局片段用靜態包含,業務模組用動態包含或 <c:import>,配合 EL/JSTL 實現關注點分離。