首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Cookie 被禁用時 Session 追蹤解決方案:URL 重寫技術實作

     編輯:Java 相關知識

問題背景

Session 依賴 Cookie 傳遞 JSESSIONID。若瀏覽器禁用 Cookie,伺服器無法識別用戶 Session,導致每次請求都建立新 Session。

Java EE 解決方案:URL 重寫

Servlet API 提供兩個方法自動在 URL 後附加 jsessionid=xxx:

  • response.encodeURL(String url):用於**超連結**、**表單 action** 等普通跳轉。
  • response.encodeRedirectURL(String url):用於 response.sendRedirect() **重定向**場景。

實作範例

Servlet 1:儲存資料並跳轉

@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);
    }
}

Servlet 2:讀取資料

@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);
    }
}

手動持久化 JSESSIONID (可選)

若需關閉瀏覽器後保持 Session,可手動寫入 Cookie:

Cookie cookie = new Cookie("JSESSIONID", session.getId());
cookie.setMaxAge(30 * 60); // 30 分鐘
cookie.setPath("/");
resp.addCookie(cookie);

注意事項

  1. 所有頁面跳轉 URL **必須**經過 encodeURL 或 encodeRedirectURL 處理。
  2. encodeURL 若發現客戶端支援 Cookie,則**不會**附加 jsessionid,自動適配。
  3. 靜態資源 (CSS/JS/圖片) 不需重寫。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved