JSP容器自動實例化九大隱含對象,無需聲明即可直接使用。它們是Servlet API在JSP層面的投影,掌握其核心方法與適用場景,能讓頁面邏輯更簡潔、更符合Web語義。本文速查九大對象並深度講解session會話管理實戰。
| 對象 | 類型/接口 | 核心用途 | 關鍵方法示例 |
|---|---|---|---|
| request | HttpServletRequest | 封裝客戶端請求參數、頭、Cookie | getParameter() getHeader() getCookies() getRemoteAddr() |
| response | HttpServletResponse | 控制響應頭、狀態碼、重定向、輸出流 | sendRedirect() setContentType() addCookie() setStatus() |
| pageContext | PageContext | 頁面屬性管理、訪問其他隱含對象、轉發/包含 | setAttribute(name,val,scope) include() forward() getOut() |
| session | HttpSession | 用戶會話狀態維持(登錄態、購物車、向導數據) | setAttribute() getAttribute() invalidate() setMaxInactiveInterval() |
| application | ServletContext | 全局應用上下文(配置、連接池、計數器、緩存) | getInitParameter() getRealPath() log() setAttribute() |
| out | JspWriter | 頁面輸出流、緩衝區控制 | print() println() clear() getBufferSize() isAutoFlush() |
| config | ServletConfig | Servlet初始化參數 | getInitParameter() getServletName() getServletContext() |
| page | Object (this) | 當前JSP對應的Servlet實例 | 調用Servlet定義的方法 |
| exception | Throwable | 錯誤頁面(isErrorPage="true")可用的異常對象 | getMessage() printStackTrace() |
模擬三步問卷:姓名 → 喜好 → 結果展示。
<form method="POST" action="q2.jsp">
請輸入您的姓名:<input type="text" name="thename">
<input type="submit" value="SUBMIT">
</form>
<%@ page language="java" %>
<%
String name = request.getParameter("thename");
session.setAttribute("thename", name); // 關鍵:存入會話
%>
<html><body>
您的姓名是:<%= name %><p>
<form method="POST" action="q3.jsp">
您喜歡吃什麼?<input type="text" name="food">
<input type="submit" value="SUBMIT">
</form>
</body></html>
<%@ page language="java" %>
<%
String food = request.getParameter("food");
String name = (String) session.getAttribute("thename"); // 跨請求讀取
%>
<html><body>
您的姓名是:<%= name %><p>
您喜歡吃:<%= food %>
</body></html>
驗證:直接訪問q3.jsp(未經q2.jsp),name為null;走完流程,姓名跨頁保持——證明session生命週期超越單次請求。
session.invalidate();敏感操作後重新生成Session ID防固定攻擊。web.xml<session-timeout>15</session-timeout>(分鐘),或代碼session.setMaxInactiveInterval(900)(秒)。<%@ page session="false" %>減輕容器負擔。web.xml配置<session-config><cookie-config><http-only>true</http-only><secure>true</secure></cookie-config></session-config>。九大內置對象是JSP與Servlet容器交互的介面契約,session更是有狀態Web應用的基石。理解其生命週期邊界,比記憶API更重要。