JSP 本質是 Servlet,生命週期與 Servlet 高度相似,額外增加編譯階段。
| 階段 | 對應 Servlet | 關鍵動作 | 開發者介入點 |
|---|---|---|---|
| 1. 編譯 | — (JSP 獨有) | .jsp → .java (Servlet) → .class | 預編譯部署 (JSPC) |
| 2. 初始化 | init() | 載入類別、實例化、jspInit() | 覆寫 jspInit() |
| 3. 執行/服務 | service() | 每請求呼叫 _jspService() | 頁面邏輯 (Scriptlet/標籤/EL) |
| 4. 銷毀 | destroy() | jspDestroy()、釋放資源、卸載類別 | 覆寫 jspDestroy() |
public final class hello_jsp extends HttpJspBase {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
public void _jspInit() { /* jspInit() 內容 */ }
public void _jspDestroy() { /* jspDestroy() 內容 */ }
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PageContext pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
JspWriter out = pageContext.getOut();
// 模板文字 → out.write()
out.write("\r\n<html>\r\n<body>\r\n");
// Scriptlet 直接內嵌
String name = request.getParameter("name");
if (name != null) {
out.write("Hello, " + name + "!");
}
out.write("\r\n</body>\r\n</html>\r\n");
}
}
<%!
private DataSource dataSource;
public void jspInit() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
} catch (NamingException e) {
throw new RuntimeException("資料源初始化失敗", e);
}
}
%>
<%!
public void jspDestroy() {
if (dataSource != null) {
try { dataSource.close(); } catch (Exception e) { log("關閉資料源失敗", e); }
}
// 關閉其他資源...
}
%>
[請求到達]
↓
[檢查是否需編譯] → 是 → [解析 JSP] → [生成 Servlet.java] → [javac 編譯] → [載入類別]
↓ 否
[載入/實例化 Servlet] → [jspInit() 一次]
↓
[每請求: _jspService(req, resp)] ←←←←←←←←←←←←←←
↓
[容器關閉/重新部署]
↓
[jspDestroy() 一次]
↓
[卸載類別、釋放資源]