JSP容器自動實例化九大隱含對象,直接可用無需聲明。它們是Servlet API在頁面層的投影,精通其核心方法與適用場景,能讓頁面邏輯簡潔、語義清晰。本文逐個拆解九大對象的類型、關鍵API、典型用法。
| 對象 | 實際類型/接口 | 核心職責 | 高頻方法示例 |
|---|---|---|---|
| page | Object (Servlet實例) | 當前JSP對應的Servlet實例(this) | 調用Servlet定義的方法 |
| config | ServletConfig | Servlet初始化參數 | getInitParameter() getServletName() getServletContext() |
| request | HttpServletRequest | 封裝客戶端請求:參數、頭、Cookie、屬性 | getParameter() getHeader() getCookies() getAttribute() getRemoteAddr() getRequestURI() setCharacterEncoding() |
| response | HttpServletResponse | 控制響應:狀態碼、頭、Cookie、重定向、輸出流 | sendRedirect() setContentType() addCookie() setStatus() encodeRedirectURL() |
| out | JspWriter | 頁面字符輸出流、緩衝區管理 | print()/println() clear() flush() getBufferSize() isAutoFlush() |
| session | HttpSession | 用戶會話狀態:屬性存取、生命週期控制 | setAttribute() getAttribute() invalidate() setMaxInactiveInterval() getId() isNew() |
| application | ServletContext | 全局應用上下文:初始化參數、資源路徑、日志、屬性共享 | getInitParameter() getRealPath() log() setAttribute() getMimeType() getServerInfo() |
| pageContext | PageContext | 頁面上下文:統一訪問所有作用域屬性、轉發包含、異常處理 | setAttribute(name,val,scope) findAttribute(name) include() forward() getException() getRequest()/getSession()/getApplication() |
| exception | Throwable | 錯誤頁面(isErrorPage="true")可用的異常對象 | getMessage() getLocalizedMessage() printStackTrace() |
pageContext提供跨作用域的統一屬性操作,四大作用域常量:
PageContext.PAGE_SCOPEPageContext.REQUEST_SCOPEPageContext.SESSION_SCOPEPageContext.APPLICATION_SCOPE核心方法:
void setAttribute(String name, Object value, int scope)
Object getAttribute(String name, int scope)
Object findAttribute(String name) // 依次搜索page→request→session→application
void removeAttribute(String name, int scope)
int getAttributesScope(String name) // 返回屬性所在作用域常量
Enumeration getAttributeNamesInScope(int scope)
重點深度:session會話管理鐵律
- 登入後
session.setAttribute("user", userDTO);權限攔截器檢查session.getAttribute("user")。
- 登出
session.invalidate()銷毀會話;敏感操作後session = request.getSession(true); session.setAttribute("user", user)重新生成Session ID防會話固定攻擊。
- 超時配置:
web.xml<session-timeout>15</session-timeout>(分)或代碼session.setMaxInactiveInterval(900)(秒)。
- 無狀態頁
<%@ page session="false" %>禁用Session創建。
- 集群環境:Session屬性必須實現
Serializable,開啟Sticky Session或Session Replication/Redis共享。
重點深度:request/response編碼鐵律
- 請求解碼:
request.setCharacterEncoding("UTF-8")必須在getParameter()之前調用(Filter中統一攔截最佳)。
- 響應編碼:
response.setContentType("text/html;charset=UTF-8")或response.setCharacterEncoding("UTF-8"),配合JSP<%@ page pageEncoding="UTF-8" %>三位一體。
錯誤頁面機制
<%@ page isErrorPage="true" import="java.io.*" %>
<html><body>
<h2>系統發生錯誤</h2>
<pre><% exception.printStackTrace(new PrintWriter(out)); %></pre>
</body></html>
正常頁面<%@ page errorPage="/error.jsp" %>指定錯誤頁,未捕獲異常自動轉發並暴露exception對象。
九大隱含對象是JSP與容器交互的介面契約。理解其生命週期邊界、作用域語義、線程安全特性,比背誦API更能寫出健壯代碼。