Cookie 是一小塊由伺服器生成、嵌入 HTTP 回應標頭的資料,瀏覽器接收後會以「鍵/值」對的形式儲存在客戶端的文字檔案中。後續請求同一伺服器時,瀏覽器會自動攜帶這些 Cookie,伺服器即可讀取其中的資訊。Cookie 可設定有效期限,過期的 Cookie 不會被發送。
Servlet API 提供了 javax.servlet.http.Cookie 類,封裝了 Cookie 的常用操作。開發者可以建立新的 Cookie、設定其名稱、值、有效期等屬性,再透過 HttpServletResponse.addCookie() 送回瀏覽器;也能從 HttpServletRequest.getCookies() 取得陣列形式的所有 Cookie。
以下示範如何在 Servlet 中讀取並顯示所有 Cookie 資訊:
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowCookies extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, java.io.IOException {
resp.setContentType("text/html;charset=UTF-8");
java.io.PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
out.println("<html><head><title>Servlet Cookie 資訊</title></head><body>");
if (cookies == null || cookies.length == 0) {
out.println("沒有 Cookies");
} else {
out.println("<center><h1>回應訊息中的 Cookies 資訊</h1>");
out.println("<table border='1'><tr><th>Name</th><th>Value</th><th>Comment</th><th>Max Age</th></tr>");
for (Cookie c : cookies) {
out.println("<tr><td>" + c.getName() + "</td><td>" +
c.getValue() + "</td><td>" + c.getComment() + "</td><td>" + c.getMaxAge() + "</td></tr>");
}
out.println("</table></center>");
}
out.println("</body></html>");
out.flush();
}
public void init(ServletConfig cfg) throws ServletException { super.init(cfg); }
public void destroy() { super.destroy(); }
}
Cookie 涉及伺服器端與客戶端的雙向傳輸,因此存在安全性風險。開發時應注意:
HttpOnly 與 Secure 標誌,防止 XSS 與中間人攻擊。Domain 與 Path,縮小暴露範圍。