Session 依賴 Cookie 傳遞 JSESSIONID。若瀏覽器禁用 Cookie,伺服器無法識別用戶 Session,導致每次請求都建立新 Session。
Servlet API 提供兩個方法自動在 URL 後附加 jsessionid=xxx:
response.encodeURL(String url):用於**超連結**、**表單 action** 等普通跳轉。response.encodeRedirectURL(String url):用於 response.sendRedirect() **重定向**場景。@WebServlet("/session1")
public class Session1Servlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession();
session.setAttribute("ip", req.getRemoteAddr());
// 超連結跳轉使用 encodeURL
String link = resp.encodeURL(req.getContextPath() + "/session2");
resp.getWriter().println("IP 已儲存,<a href='" + link + "'>點此查看</a>");
// 若用重定向:
// String redirectUrl = resp.encodeRedirectURL(req.getContextPath() + "/session2");
// resp.sendRedirect(redirectUrl);
}
}
@WebServlet("/session2")
public class Session2Servlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession(false); // 不自動創建
String ip = (session != null) ? (String) session.getAttribute("ip") : "Session 遺失";
resp.getWriter().println("您的 IP:" + ip);
}
}
若需關閉瀏覽器後保持 Session,可手動寫入 Cookie:
Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(30 * 60); // 30 分鐘
cookie.setPath("/");
resp.addCookie(cookie);
encodeURL 或 encodeRedirectURL 處理。encodeURL 若發現客戶端支援 Cookie,則**不會**附加 jsessionid,自動適配。