B/S 架構下,瀏覽器發起 HTTP 請求(TCP/IP 協議棧,應用層 HTTP/1.1),Tomcat 將原始報文封裝為 HttpServletRequest 物件,派發至對應 Servlet 的 doGet()/doPost() 方法。
getMethod():GET/POST/PUT/DELETE 等getRequestURI() / getRequestURL():資源路徑getProtocol():HTTP/1.1getHeader(String name):單值getHeaders(String name):多值(如 Cookie)getHeaderNames():所有頭名稱枚舉getParameter(String name):表單/查詢字串參數(自動解碼)getParameterMap():所有參數 MapgetInputStream():原始二進制流(JSON/XML 請求體)getReader():字元流(需正確設定編碼)// POST 請求體編碼(必須在讀取參數前調用)
request.setCharacterEncoding("UTF-8");
// GET 參數編碼(Tomcat 8+ 預設 UTF-8,舊版需配置 server.xml URIEncoding)
// 或使用 Filter 統一處理
Servlet 透過 HttpServletResponse 設定狀態碼、頭、輸出內容。
| 頭部 | 說明 | 典型值 |
|---|---|---|
| Content-Type | MIME 類型與編碼 | text/html;charset=UTF-8 |
| Location | 重定向地址 | /login.jsp |
| Set-Cookie | 下發 Cookie | JSESSIONID=xxx; Path=/; HttpOnly |
| Cache-Control | 快取控制 | no-cache, no-store, must-revalidate |
| Content-Disposition | 下載檔名 | attachment; filename="report.pdf" |
getWriter():字元輸出(HTML/JSON),需先 setContentType("text/html;charset=UTF-8")getOutputStream():二進制輸出(檔案下載、圖片),不可與 getWriter() 混用