一.服務器端獲取Session對象依賴於客戶端攜帶的Cookie中的JSESSIONID數據。如果用戶把瀏覽器的隱私級別調到最高,這時瀏覽器是不會接受Cookie、這樣導致永遠在服務器端都拿不到的JSESSIONID信息。這樣就導致服務器端的Session使用不了。
Java針對Cookie禁用,給出了解決方案,依然可以保證JSESSIONID的傳輸。
Java中給出了再所有的路徑的后面拼接JSESSIONID信息。
在 Session1Servlet中,使用response.encodeURL(url) 對超鏈接路徑拼接 session的唯一標識
|
1
2
3
4
5
6
7
|
// 當點擊 的時候跳轉到 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)。
如果我們使用的重定向技術,這時必須使用下面方法完成:其實就是在路徑后面拼接了 Session的唯一標識 JSESSIONID。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
// 重定向到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地址保存成功,想看 請<a href='" + path + "'>點擊</a>");
// 重定向到session2
String path = response.encodeRedirectURL(
"/day11/session2"
);
System.out.println(
"重定向編碼后的路徑:"
+ path);
response.sendRedirect(path);
}
|


