| 對象 | 類型 | 作用域 | 核心用途 |
|---|---|---|---|
| request | HttpServletRequest | 請求 | 獲取參數、Header、屬性、轉發 |
| response | HttpServletResponse | 頁面 | 設置狀態、Header、Cookie、重定向、輸出流 |
| session | HttpSession | 會話 | 用戶狀態、購物車、登錄態、屬性存取 |
| application | ServletContext | 應用 | 全局配置、緩存、計數器、資源路徑 |
| out | JspWriter | 頁面 | 輸出內容到瀏覽器、緩衝區控制 |
| pageContext | PageContext | 頁面 | 訪問所有內置對象、屬性作用域管理、異常處理 |
| config | ServletConfig | 頁面 | 初始化參數、ServletContext 獲取 |
| page | Object (this) | 頁面 | 當前 JSP 頁面實例,極少直接使用 |
| exception | Throwable | 頁面 | 錯誤頁面獲取異常信息(需 isErrorPage=true) |
<!-- 獲取參數 -->
${param.username} <!-- EL 表達式推薦 -->
<%= request.getParameter("username") %>
<!-- 設置屬性供轉發頁面使用 -->
<% request.setAttribute("user", user); %>
<!-- 獲取 Header -->
${header['User-Agent']}
<!-- 請求轉發 -->
<% request.getRequestDispatcher("/detail.jsp").forward(request, response); %>
中文亂碼解決:request.setCharacterEncoding("UTF-8")(必須在讀取參數前調用)。
<!-- 重定向 -->
<% response.sendRedirect("/login.jsp"); %>
<!-- 設置 Content-Type -->
<% response.setContentType("application/json;charset=UTF-8"); %>
<!-- 設置 Cookie -->
<%
Cookie c = new Cookie("token", "abc123");
c.setMaxAge(3600);
c.setPath("/");
response.addCookie(c);
%>
<!-- 直接輸出 -->
<% response.getWriter().write("{\"code\":200}"); %>
<!-- 存取屬性 -->
<% session.setAttribute("loginUser", user); %>
${sessionScope.loginUser.name}
<!-- 判斷新會話 -->
<% if (session.isNew()) { ... } %>
<!-- 設置超時(秒) -->
<% session.setMaxInactiveInterval(1800); %> <!-- 30分鐘 -->
<!-- 銷毀 -->
<% session.invalidate(); %>
原理:Server 分配 JSESSIONID,客戶端 Cookie 攜帶,Server 內存/Redis 存儲數據。
<%-- 初始化緩存(通常在 ServletContextListener 中) --%>
<% application.setAttribute("configMap", loadConfig()); %>
<%-- 讀取 --%>
${applicationScope.configMap.siteName}
<%-- 獲取真實路徑 --%>
<% String path = application.getRealPath("/WEB-INF/data.txt"); %>
<% out.print("Hello"); %>
<% out.println("World"); %>
<% out.clear(); %> <!-- 清空緩衝區 -->
<% out.flush(); %> <!-- 強制刷新 -->
注意:out 是 JspWriter,帶緩衝區,異於 response.getWriter()(直接輸出)。
<%-- 獲取其他內置對象 --%>
<%
HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
HttpSession sess = pageContext.getSession();
ServletContext app = pageContext.getServletContext();
JspWriter out = pageContext.getOut();
%>
<%-- 屬性作用域操作 --%>
<% pageContext.setAttribute("key", "val", PageContext.REQUEST_SCOPE); %>
<% Object val = pageContext.findAttribute("key"); %> <!-- 按優先級查找 -->
<%-- 包含/轉發 --%>
<% pageContext.include("/fragment.jsp"); %>
<% pageContext.forward("/target.jsp"); %>
<!-- web.xml 中配置 -->
<servlet>
<init-param>
<param-name>adminEmail</param-name>
<param-value>admin@example.com</param-value>
</init-param>
</servlet>
<% String email = config.getInitParameter("adminEmail"); %>
<%-- errorPage.jsp (page 指令 isErrorPage="true") --%>
<%@ page isErrorPage="true" import="java.io.PrintWriter" %>
<h1>系統錯誤</h1>
<pre><% exception.printStackTrace(new PrintWriter(out)); %></pre>
<%-- 正常頁面指定錯誤頁 --%>
<%@ page errorPage="errorPage.jsp" %>
pageContext.findAttribute("name")
// 等價於依次查找:
// 1. PageScope (pageContext)
// 2. RequestScope (request)
// 3. SessionScope (session)
// 4. ApplicationScope (application)
// 找到即返回,否則 null
${...}) 訪問數據<c:if>, <c:forEach>) 控制邏輯<% ... %> 大段 Java 代碼九大內置對象是 JSP 隱式提供的便利工具,理解其類型、作用域、核心 API、相互關係是掌握 JSP 開發的基礎。現代項目建議:Controller 處理邏輯 → Model 裝載數據 → JSP/Thymeleaf 純展示,內置對象主要在遷移老項目或簡單頁面中直接使用。