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