| 變量名 | 類型 | 作用域 | 核心用途 | 生命週期 |
|---|---|---|---|---|
| request | HttpServletRequest | 請求 | 取參數、Header、屬性、轉發/包含 | 單次請求 |
| response | HttpServletResponse | 頁面 | 設狀態碼、Header、Cookie、重導向、輸出流 | 單次請求 |
| out | JspWriter | 頁面 | 輸出內容 (緩衝版 PrintWriter),控制緩衝/flush | 單次請求 |
| session | HttpSession | 會話 | 用戶狀態、購物車、登入資訊 (自動建立) | 預設 30 分鐘無操作 |
| application | ServletContext | 應用 | 全域共享資料、初始化參數、資源路徑、日誌 | Web 應用存活期間 |
| config | ServletConfig | 頁面 | Servlet 初始化參數 (` | Servlet 實例存活期間 |
| pageContext | PageContext | 頁面 | 統一訪問其他 8 大物件、屬性跨作用域查找、forward/include | 單次請求 |
| page | Object (this) | 頁面 | 當前 Servlet 實例引用,極少直接使用 | 單次請求 |
| exception | Throwable | 頁面 | **僅錯誤頁面** (`isErrorPage="true"`) 可用,捕獲未處理異常 | 錯誤處理請求期間 |
| 場景 | 推薦物件/方法 |
|---|---|
| 讀取表單/查詢字串參數 | `request.getParameter()` |
| 設定響應編碼/內容類型 | `response.setContentType("text/html;charset=UTF-8")` (或 page 指令) |
| Scriptlet 中輸出 HTML 片段 | `out.print()/println()` |
| 登入後存用戶資訊 | `session.setAttribute("user", userVO)` |
| 全域快取熱門商品列表 | `application.setAttribute("hotProducts", list)` (配合同步/快取框架) |
| 讀取 web.xml context-param | `application.getInitParameter("configKey")` |
| 在 Tag 檔/工具類中獲取 request/response | `pageContext.getRequest()`, `pageContext.getResponse()` |
| 錯誤頁面顯示異常堆疊 | `exception.printStackTrace(response.getWriter())` |