首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP九大內置對象速查手冊:核心API與Session會話管理實戰

     編輯:關於JSP

JSP容器自動實例化九大隱含對象,無需聲明即可直接使用。它們是Servlet API在JSP層面的投影,掌握其核心方法與適用場景,能讓頁面邏輯更簡潔、更符合Web語義。本文速查九大對象並深度講解session會話管理實戰。

九大內置對象速查表

對象類型/接口核心用途關鍵方法示例
requestHttpServletRequest封裝客戶端請求參數、頭、CookiegetParameter() getHeader() getCookies() getRemoteAddr()
responseHttpServletResponse控制響應頭、狀態碼、重定向、輸出流sendRedirect() setContentType() addCookie() setStatus()
pageContextPageContext頁面屬性管理、訪問其他隱含對象、轉發/包含setAttribute(name,val,scope) include() forward() getOut()
sessionHttpSession用戶會話狀態維持(登錄態、購物車、向導數據)setAttribute() getAttribute() invalidate() setMaxInactiveInterval()
applicationServletContext全局應用上下文(配置、連接池、計數器、緩存)getInitParameter() getRealPath() log() setAttribute()
outJspWriter頁面輸出流、緩衝區控制print() println() clear() getBufferSize() isAutoFlush()
configServletConfigServlet初始化參數getInitParameter() getServletName() getServletContext()
pageObject (this)當前JSP對應的Servlet實例調用Servlet定義的方法
exceptionThrowable錯誤頁面(isErrorPage="true")可用的異常對象getMessage() printStackTrace()

深度實戰:Session多頁面會話傳遞

模擬三步問卷:姓名 → 喜好 → 結果展示。

q1.html:收集姓名

<form method="POST" action="q2.jsp">
  請輸入您的姓名:<input type="text" name="thename">
  <input type="submit" value="SUBMIT">
</form>

q2.jsp:存入Session、詢問喜好

<%@ 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>

q3.jsp:跨頁面讀取Session

<%@ 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最佳實踐

  • 少存大對象:序列化/反序列化開銷大,集群下同步成本高。
  • 及時失效:登出調用session.invalidate();敏感操作後重新生成Session ID防固定攻擊。
  • 設置超時:web.xml<session-timeout>15</session-timeout>(分鐘),或代碼session.setMaxInactiveInterval(900)(秒)。
  • 無狀態頁面禁用Session:<%@ 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更重要。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved