一.服務器端獲取Session對象依賴于客戶端攜帶的Cookie中的JSESSIONID數據。如果用戶把瀏覽器的隱私級別調到最高,這時瀏覽器是不會接受Cookie、這樣導致永遠在服務器端都拿不到的JSESSIONID信息。這樣就導致服務器端的Session使用不了。
Java針對Cookie禁用,給出了解決方案,依然可以保證JSESSIONID的傳輸。
Java中給出了再所有的路徑的后面拼接JSESSIONID信息。
在 Session1Servlet中,使用response.encodeURL(url) 對超鏈接路徑拼接 session的唯一標識
// 當點擊 的時候跳轉到 session2
response.setContentType("text/html;charset=utf-8");
//此方法會在路徑后面自動拼接sessionId
String path = response.encodeURL("/day11/session2");
System.out.println(path);
//頁面輸出
response.getWriter().println("ip地址保存成功,想看 請點擊");
二.在response對象中的提供的encodeURL方法它只能對頁面上的超鏈接或者是form表單中的action中的路徑進行重寫(拼接JSESSIONID)。
如果我們使用的重定向技術,這時必須使用下面方法完成:其實就是在路徑后面拼接了 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對應的cookie持久化,關閉瀏覽器再次訪問session中的數據依然存在
// 創建cookie
Cookie cookie =new?Cookie("JSESSIONID", session.getId());
// 設置cookie的最大生存時間
cookie.setMaxAge(60 * 30);
// 設置有效路徑
cookie.setPath("/");
// 發送cookie
response.addCookie(cookie);
// 當點擊 的時候跳轉到 session2
// response.setContentType("text/html;charset=utf-8");
// String path = response.encodeURL("/day11/session2");
// System.out.println(path);
// response.getWriter().println("ip地址保存成功,想看 請點擊");
// 重定向到session2
String path = response.encodeRedirectURL("/day11/session2");
System.out.println("重定向編碼后的路徑:"?+ path);
response.sendRedirect(path);
}
以上所述是小編給大家介紹的java中Cookie被禁用后Session追蹤問題,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!
原文鏈接:http://blog.csdn.net/wearetheworld1/article/details/60463652
如對本文有疑問,請提交到交流社區,廣大熱心網友會為你解答!! 點擊進入社區