ServletConfig (含初始參數) → 呼叫 init(config)。GenericServlet 已封裝 ServletConfig,提供 getInitParameter() 等便利方法。init() 而非有參版本,避免忘記 super.init(config)。ServletContext,可跨 Servlet 共享資料。getRequestDispatcher("/path") (路徑必須以 / 開頭)、getResourceAsStream() 讀取資源檔、setAttribute/getAttribute 全域共享。web.xml 設定 <context-param>,配合 ServletContextListener 初始化資源。| 監聽器介面 | 監聽事件 | 典型用途 |
|---|---|---|
| ServletContextListener | 應用啟動/銷毀 | 載入配置、初始化連線池、啟動排程 |
| ServletContextAttributeListener | 屬性增/刪/改 | 審計、快取同步 |
| HttpSessionListener | Session 建立/失效 | 在線人數統計、Session 資料清理 |
| HttpSessionAttributeListener | Session 屬性變更 | 同步 Session 資料至叢集 |
| HttpSessionBindingListener | 物件綁定/解綁 Session | 實作於值物件自身,感知生命週期 |
| HttpSessionActivationListener | Session 鈍化/活化 (分布式) | 叢集環境 Session 遷移處理 |
| ServletRequestListener | 請求開始/結束 | 請求耗時統計、ThreadLocal 清理 |
| ServletRequestAttributeListener | 請求屬性變更 | 除錯、日誌記錄 |
Filter,配置 @WebFilter 或 web.xml。init → 多次 doFilter → destroy。doFilter(req, res, chain):前置處理 → chain.doFilter(req, res) (放行) → 後置處理。chain.doFilter 即為**攔截** (如權限檢查失敗直接重定向)。dispatcherTypes 區分 REQUEST/FORWARD/INCLUDE/ERROR/ASYNC。HttpServletRequestWrapper:解決請求體多次讀取、統一編碼、參數過濾 (如 XSS 過濾)。HttpServletResponseWrapper:響應壓縮 (GZIP)、自訂輸出流。request.startAsync() 返回 AsyncContext,釋放容器執行緒。asyncContext.complete() 或 dispatch()。asyncSupported=true。