一.服務器端獲取Session對象依賴於客戶端攜帶的Cookie中的JSESSIONID數據。若是用戶把瀏覽器的隱私級別調到最高,這時瀏覽器是不會接受Cookie、這樣致使永遠在服務器端都拿不到的JSESSIONID信息。這樣就致使服務器端的Session使用不了。 html
Java針對Cookie禁用,給出瞭解決方案,依然能夠保證JSESSIONID的傳輸。java
Java中給出了再全部的路徑的後面拼接JSESSIONID信息。web
在 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);
}
|