- 相關(guān)推薦
java中Cookie被禁用后Session追蹤問題
這篇文章主要介紹了Java中Cookie被禁用后Session追蹤問題,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
一.服務(wù)器端獲取Session對象依賴于客戶端攜帶的Cookie中的JSESSIONID數(shù)據(jù)。如果用戶把瀏覽器的隱私級別調(diào)到最高,這時瀏覽器是不會接受Cookie、這樣導(dǎo)致永遠在服務(wù)器端都拿不到的JSESSIONID信息。這樣就導(dǎo)致服務(wù)器端的Session使用不了。
Java針對Cookie禁用,給出了解決方案,依然可以保證JSESSIONID的傳輸。
Java中給出了再所有的路徑的后面拼接JSESSIONID信息。
在 Session1Servlet中,使用response.encodeURL(url) 對超鏈接路徑拼接 session的唯一標識
// 當(dāng)點擊 的時候跳轉(zhuǎn)到 session2
response.setContentType("text/html;charset=utf-8");
//此方法會在路徑后面自動拼接sessionId
String path = response.encodeURL("/day11/session2");
System.out.println(path);
//頁面輸出
response.getWriter().println("ip地址保存成功,想看 請<a href='" + path + "'>點擊</a>");
二.在response對象中的提供的encodeURL方法它只能對頁面上的超鏈接或者是form表單中的action中的路徑進行重寫(拼接JSESSIONID)。
如果我們使用的重定向技術(shù),這時必須使用下面方法完成:其實就是在路徑后面拼接了 Session的唯一標識 JSESSIONID。
// 重定向到session2
String path = response.encodeRedirectURL("/day11/session2");
System.out.println("重定向編碼后的路徑:" + path);
response.sendRedirect(path);
session2代碼,獲得session1傳過來的ID
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 需求:從session容器中取出ip
// 獲得session對象
HttpSession session = request.getSession();
// 獲取ip地址
String ip = (String) session.getAttribute("ip");
// 將ip打印到瀏覽器中
response.setContentType("text/html;charset=utf-8");
response.getWriter().println("IP:" + ip);
}
session1代碼
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 需求:將ip保存到session中
// 獲取session
HttpSession session = request.getSession();
// 獲得ip
String ip = request.getRemoteAddr();
// 將ip保存到session中
session.setAttribute("ip", ip);
// 需求2:手動的將 session對應(yīng)的cookie持久化,關(guān)閉瀏覽器再次訪問session中的數(shù)據(jù)依然存在
// 創(chuàng)建cookie
Cookie cookie = new Cookie("JSESSIONID", session.getId());
// 設(shè)置cookie的最大生存時間
cookie.setMaxAge(60 * 30);
// 設(shè)置有效路徑
cookie.setPath("/");
// 發(fā)送cookie
response.addCookie(cookie);
// 當(dāng)點擊 的時候跳轉(zhuǎn)到 session2
// response.setContentType("text/html;charset=utf-8");
// String path = response.encodeURL("/day11/session2");
// System.out.println(path);
// response.getWriter().println("ip地址保存成功,想看 請<a href='" + path + "'>點擊</a>");
// 重定向到session2
String path = response.encodeRedirectURL("/day11/session2");
System.out.println("重定向編碼后的路徑:" + path);
response.sendRedirect(path);
}
以上所述是小編給大家介紹的java中Cookie被禁用后Session追蹤問題,希望對大家有所幫助!
【java中Cookie被禁用后Session追蹤問題】相關(guān)文章:
PHP創(chuàng)建和使用session cookie變量05-16
Java中finally的問題09-28
Session在PHP中的使用07-24
關(guān)于Java讀寫Cookie記錄的方法08-19
如何使用php中session08-27
PHP中COOKIE支持詳解09-15
php中cookie的使用方法09-27