HttpServlet 繼承自 GenericServlet,是 Servlet 開發的核心基類。本文透過 SnoopServlet 範例,示範如何攔截並展示完整的 HTTP 請求資訊——包含初始化參數、Header、Cookie、Session、請求屬性等,是除錯與監控的利器。
部署後訪問 https://localhost:8080/examples/servlet/SnoopServlet,將輸出純文字格式的完整請求報告,涵蓋:
getInitParameterNames)ServletContext)request.getAttributeNames)getParameterNames/getParameterValues)getHeaderNames)getCookies)isSecure、認證類型、HTTP 方法、遠端用戶getRequestURI、getContextPath、getServletPath、getPathInfo、getPathTranslated、getQueryString| 方法 | 回傳含義 |
|---|---|
getRequestURI() | 請求 URI(不含主機部份) |
getPathInfo() | Servlet 路徑後的額外路徑資訊 |
getPathTranslated() | 對應的伺服器端絕對檔案路徑 |
getContextPath() | Web 應用程式的 Context Path |
getServletPath() | 對應到此 Servlet 的路徑 |
public class SnoopServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain"); // 純文字輸出,易讀易解析
PrintWriter out = response.getWriter();
// 1. 輸出各類資訊區塊,統一採用 Enumeration 迭代
out.println("Servlet init parameters:");
Enumeration e = getInitParameterNames();
while (e.hasMoreElements()) { ... }
// 2. Context 參數與屬性
ServletContext context = getServletContext();
// ... 類似迭代輸出
// 3. 請求屬性、參數、Header、Cookie
// ... 逐一迭代輸出
// 4. 核心請求資訊(單值直接輸出)
out.println("Protocol: " + request.getProtocol());
// ...
// 5. Session 資訊
HttpSession session = request.getSession();
out.println("Current Session Id: " + session.getId());
// ... 輸出 Session 屬性
}
}
WEB-INF/servlets 目錄。web.xml 註冊 Servlet 映射(或依伺服器預設規則)。SnoopServlet 是 Servlet 開發者的「聽診器」,快速診斷請求傳遞、Session 管理、參數解析等常見問題。