部署於本地 8080 端口,邏輯:無 Cookie 則下發、有則複用。以 localhost:8080 訪問正常,Cookie 共享;以 127.0.0.1:8080 訪問每次 Cookie 皆不同,無法獲取先前設定值。
localhost:8080 下發 Cookie 域為 localhost。127.0.0.1:8080 下發 Cookie 域為 127.0.0.1:8080(含端口),導致 Servlet request.getCookies() 永遠讀不到。127.0.0.1(不含端口),故 Session 正常。String host = request.getHeader("host"); // 可能包含 "127.0.0.1:8080"
Cookie cookie = new Cookie("uid", uid);
cookie.setDomain(host); // 錯誤:包含端口
cookie.setMaxAge(93312000);
response.addCookie(cookie);
String host = request.getHeader("host");
if (host.indexOf(":") > -1) {
host = host.split(":")[0]; // 去除端口,僅保留域名/IP
}
cookie.setDomain(host);
// 或直接不調用 setDomain(),瀏覽器預設為當前 host(不含端口)
app.example.com),避免 IP/localhost 混用。setPath("/") 確保全路徑共享。setSecure(true)、setHttpOnly(true) 提升安全性。