JSP 容器自動建立九個隱含物件,開發者可直接在 Scriptlet、EL 運算式、JSTL 中使用,無需宣告。理解其型別、範圍與常用方法,是撰寫高效 JSP 的基礎。
| 物件名稱 | Java 型別 | 範圍 | 主要用途 |
|---|---|---|---|
request | HttpServletRequest | Request | 接收請求參數、標頭、屬性、轉發 |
response | HttpServletResponse | Page | 設定狀態碼、標頭、Cookie、輸出流 |
out | JspWriter | Page | 輸出文字內容至回應主體 |
session | HttpSession | Session | 跨請求儲存用戶狀態 (登入資訊、購物車) |
application | ServletContext | Application | 全域共享資料、初始化參數、資源存取 |
config | ServletConfig | Page | Servlet/JSP 初始化參數 |
pageContext | PageContext | Page | 存取所有範圍屬性、轉發、包含、錯誤處理 |
page | Object (this) | Page | 當前 JSP 頁面實例 (極少直接使用) |
exception | Throwable | Page | 錯誤頁面 (isErrorPage="true") 取得例外 |
getParameter(), getParameterValues(), getParameterMap()setAttribute(), getAttribute() (Request 範圍,Forward 共享)setStatus(), sendRedirect(), sendError()setHeader(), addHeader(), setContentType()addCookie()getWriter(), getOutputStream()flushBuffer(), reset(), isCommitted()<%
out.print("不換行輸出");
out.println("換行輸出");
out.write("字串");
out.flush(); // 強制輸出緩衝區
%>
PrintWriter 大部分方法page 指令 buffer="8kb", autoFlush="true")IOException (PrintWriter 不拋出)<%
session.setAttribute("loginUser", user); // 存入
User u = (User) session.getAttribute("loginUser"); // 取出
session.removeAttribute("tempData"); // 移除
session.invalidate(); // 銷毀整個 Session
session.setMaxInactiveInterval(30*60); // 設定逾時 30 分鐘
%>
5. application (ServletContext)
<%
// 全域共享資料
application.setAttribute("onlineCount", 100);
Integer count = (Integer) application.getAttribute("onlineCount");
// 初始化參數 (web.xml )
String dbUrl = application.getInitParameter("dbUrl");
// 資源路徑
String realPath = application.getRealPath("/WEB-INF/config.xml");
InputStream is = application.getResourceAsStream("/WEB-INF/config.xml");
// 跨應用轉發 (需 crossContext="true")
// RequestDispatcher rd = application.getRequestDispatcher("/otherApp/page.jsp");
%>
6. config (ServletConfig)
<%
// JSP 初始化參數 (web.xml )
String adminEmail = config.getInitParameter("adminEmail");
String servletName = config.getServletName(); // JSP 編譯後的 Servlet 名稱
%>
較少直接使用,常見於框架初始化。
7. pageContext (PageContext) - 萬用鑰匙
<%
// 存取四大範圍屬性
pageContext.setAttribute("pageVar", "P", PageContext.PAGE_SCOPE);
pageContext.setAttribute("reqVar", "R", PageContext.REQUEST_SCOPE);
pageContext.setAttribute("sessVar", "S", PageContext.SESSION_SCOPE);
pageContext.setAttribute("appVar", "A", PageContext.APPLICATION_SCOPE);
// 尋找屬性 (依範圍優先序: Page → Request → Session → Application)
Object val = pageContext.findAttribute("name");
// 移除特定範圍屬性
pageContext.removeAttribute("name", PageContext.SESSION_SCOPE);
// 取得其他隱含物件
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
HttpSession sess = pageContext.getSession();
ServletContext app = pageContext.getServletContext();
JspWriter out = pageContext.getOut();
// 包含/轉發 (等同 jsp:include / jsp:forward)
pageContext.include("/fragment.jsp");
pageContext.forward("/target.jsp");
// 錯誤處理
pageContext.handlePageException(new RuntimeException("錯誤"));
%>
8. page (Object)
this)<%@ page isErrorPage="true" %>) 可用exception.getMessage(), exception.printStackTrace()EL 提供 11 個隱含物件 (含 param/header/cookie/initParam 等 Map):
| EL 隱含物件 | 型別 | 對應 JSP 物件 / 說明 |
|---|---|---|
pageContext | PageContext | 同 JSP pageContext |
requestScope | Map | Request 範圍屬性 Map |
sessionScope | Map | Session 範圍屬性 Map |
applicationScope | Map | Application 範圍屬性 Map |
param | Map<String,String> | 單一參數值 (request.getParameter()) |
paramValues | Map<String,String[]> | 多值參數 (getParameterValues()) |
header | Map<String,String> | 單一標頭值 |
headerValues | Map<String,String[]> | 多值標頭 |
cookie | Map<String,Cookie> | Cookie Map (名稱→Cookie 物件) |
initParam | Map<String,String> | Context 初始化參數 |
| 資料性質 | 建議範圍 | 隱含物件 | 生命週期 |
|---|---|---|---|
| 單一請求處理中繼資料 | Request | request / pageContext | 一次請求 (含 Forward) |
| 用戶登入狀態、購物車 | Session | session | 瀏覽器關閉或逾時 |
| 全域配置、快取資料、線上人數 | Application | application | 伺服器啟動至關閉 |
| 頁面片段區域變數 | Page | pageContext / out | 單一 JSP 執行期間 |
<% %>) 直接操作隱含物件。