Cookie 是伺服器生成、經 HTTP 響應頭發送給瀏覽器的少量資料(鍵值對)。瀏覽器將其存儲於客戶端文本文件,後續請求同一伺服器時自動攜帶。可設定有效期,過期即銷毀。
Servlet API 提供 javax.servlet.http.Cookie 類封裝操作:
new Cookie(name, value)setMaxAge(seconds)、setPath()、setDomain()response.addCookie(cookie)Cookie[] cookies = request.getCookies()public class ShowCookies extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
out.println("<html><body>");
if (cookies == null || cookies.length == 0) {
out.println("沒有 Cookies");
} else {
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.printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%d</td></tr>",
c.getName(), c.getValue(), c.getComment(), c.getMaxAge());
}
out.println("</table>");
}
out.println("</body></html>");
}
}
安全提醒:Cookie 雙向傳輸,涉及敏感資料時需加密或改用 Session。
HttpSession 封裝 HTTP 會話,跨多個請求識別同一用戶。核心三要素:
只有實作 java.io.Serializable 的物件才能參與上述機制。
public class ShowBuy extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String[] items = {"糖果", "收音機", "練習簿"};
HttpSession session = req.getSession(true); // 獲取或建立 Session
Integer itemCount = (Integer) session.getAttribute("itemCount");
if (itemCount == null) itemCount = 0;
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
String[] selected = req.getParameterValues("item");
if (selected != null) {
for (String itemName : selected) {
itemCount++;
session.setAttribute("Item" + itemCount, itemName);
}
session.setAttribute("itemCount", itemCount);
}
out.println("<html><body><h1>購物袋內容</h1>");
for (int i = 1; i <= itemCount; i++) {
String item = (String) session.getAttribute("Item" + i);
if (item != null) out.println(item + "<br>");
}
out.println("</body></html>");
}
}
<form action='servlet/ShowBuy' method='POST'>
<input type="checkbox" name="item" value="0"> 糖果<br>
<input type="checkbox" name="item" value="1"> 收音機<br>
<input type="checkbox" name="item" value="2"> 練習簿<br>
<input type="submit" value="加入購物袋">
</form>
request.getSession() / getSession(true):獲取現有或建立新 Sessionrequest.getSession(false):僅獲取現有,不存在返回 nullsetAttribute(name, value)、getAttribute(name)、removeAttribute(name)