本文源碼:GitHub·點這里 || GitEE·點這里
一、會話跟蹤
1、場景描述
比如登錄某個購物網站,身份識別成功后,在網站下單,支付 等操作,這些操作中當前登錄用戶信息必須是共享的,這樣這些操作結果才能和登錄用戶做關聯。
2、概念簡介
可以把會話理解為客戶端與服務器之間的一次交互,在一次交互中可能會包含多次請求和響應。在JavaWeb中,從客戶端向服務器發出第一個請求開始,會話就開始了,直到客戶端關閉瀏覽器會話結束。在一個會話的多個請求中共享數據,這就是會話跟蹤技術。
二、Cookie用法詳解
1、Cookie簡介
Cookie在HTTP中通常是用來辨別用戶身份,進行會話跟蹤而儲存在用戶本地終端上的數據,一般會加密處理,由用戶客戶端計算機暫時或永久保存的信息。其結構就是一個鍵和一個值構成的。隨着服務器端的響應發送給客戶端瀏覽器。然后客戶端瀏覽器會把Cookie保存起來,當下一次再訪問服務器時把Cookie再發送給服務器。
Cookie是由服務器創建,然后通過響應發送給客戶端的鍵值對。客戶端會保存Cookie,並會標注出Cookie的來源。當客戶端向服務器發出請求時會把Cookie包含在請求中發送給服務器,這樣服務器就可以識別客戶端。
2、Cookie用法
- 創建Cookie
JavaWeb中,可以基於Servlet創建Cookie,並設置屬性。
public class CookieServletOne extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 創建Cookie
Cookie cookie = new Cookie("author","cicada");
// 設置生命周期 1小時
cookie.setMaxAge(60*60);
response.addCookie(cookie) ;
response.getWriter().print("Hello:Cookie");
}
}
訪問:http://localhost:6002/cookieServletOne
查看響應頭:
Response Header
Set-Cookie: author=cicada; Max-Age=3600;
這樣,服務器創建的Cookie在客戶端就拿到了。
- 獲取Cookie
public class CookieServletOne extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost...");
Cookie[] cookies = request.getCookies() ;
for (Cookie cookie:cookies){
System.out.println("Name:"+cookie.getName());
System.out.println("Value:"+cookie.getValue());
}
response.setContentType("text/html;charset=utf-8");
String userName = request.getParameter("userName") ;
response.getWriter().print("Hello:"+userName);
}
}
通過測試,控制台輸出:Name:author;Value:cicada
。
- 更新Cookie
更新就是指Cookie的覆蓋,如果服務器端發送重復的Cookie那么會覆蓋原有的Cookie。
public class CookieServletTwo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 創建Cookie
Cookie cookie = new Cookie("author","smile");
// 設置生命周期 2小時
cookie.setMaxAge(60*60*2);
response.addCookie(cookie) ;
response.getWriter().print("Hello:Cookie");
}
}
可以通過上面方法測試Cookie的獲取結果。
- 刪除Cookie
cookie.setMaxAge(0):生命等於0是一個特殊的值,它表示cookie被作廢。
public class CookieServletTwo extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
Cookie[] cookies = request.getCookies() ;
for (Cookie cookie:cookies){
if (cookie.getName().equals("author")){
cookie.setMaxAge(0);
response.addCookie(cookie);
}
}
String userName = request.getParameter("userName") ;
response.getWriter().print("Hello:"+userName);
}
}
這樣再測試Cookie的獲取方法,發現上面刪除的Cookie就沒有了。
3、Cookie相關API
- setMaxAge()
設置 cookie 過期的時間,秒為單位。默認情況cookie 只會在當前 session 會話中有效。
- getMaxAge()
獲取 cookie 的最大生存周期。
- getName()
獲取 cookie 的名稱。名稱在創建后不能改變。
- getValue()
獲取與 cookie 關聯的值。
- setValue(String value)
設置與cookie關聯的value值。相同的name多次設置會覆蓋。
三、Session 跟蹤
1、Session簡介
會話管理,當用戶在應用程序的Web頁之間跳轉時,存儲在Session對象中的變量將不會丟失,而是在整個用戶會話中一直存在下去。Servlet中可以把一個會話內需要共享的數據保存到HttSession對象中。四大域對象:PageContext、ServletRequest、HttpSession、ServletContext。
2、Session運行原理
- 首次使用
首次使用session時,服務器端要創建session,session是保存在服務器端,數據是保存在session中,sessionId通過Cookie發送給客戶端,且只在瀏覽器本次會話中存在,也就是說如果用戶關閉了瀏覽器,那么這個Cookie就丟失。
- 客戶端訪問
客戶端再次訪問服務器時,在請求中會帶上sessionId,服務器會通過sessionId找到對應的session,而無需再創建新的session。
- 時效性
當一個session長時間沒人使用的話,服務器會把session刪除了,這個時長在Tomcat中配置是30分鍾,可以在${CATALANA}/conf/web.xml找到這個配置,也可以在的web.xml中覆蓋這個配置!
<session-config>
<session-timeout>30</session-timeout>
</session-config>
3、相關API用法
- getSesssion()
當前會話已經存在session對象那么直接返回,如果當前會話還不存在,創建session對象並返回 。
- getAttribute(String name)
返回該 session 會話中具有指定名稱的對象 。
- getId()
分配給該 session 會話的唯一標識符的字符串。
- setAttribute(String name,Object value)
使用指定的名稱綁定一個對象到該 session 會話。
- removeAttribute(String name)
從該 session 會話移除指定名稱的對象。
4、應用案例
在網站中,經常可見的一個功能就是上次登錄時間,這個功能基於Session可以很便捷的實現。
public class SessionServletOne extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
HttpSession session = request.getSession(true) ;
Date createTime = new Date(session.getCreationTime());
Date lastAccessTime = new Date(session.getLastAccessedTime());
session.setAttribute("author","cicada");
response.getWriter().print(
"SessionId:" + session.getId() + "<br/>"+
"User Author:" + session.getAttribute("author")+"<br/>"+
"Create Time:" + dateFormat.format(createTime)+"<br/>"+
"Last Access Time:"+dateFormat.format(lastAccessTime));
}
}
訪問http://localhost:6002/sessionServletOne
頁面打印,多次訪問,查看效果。
SessionId:40C12C367CBFA7469D57E72C5C091300
User Author:cicada
Create Time:2019-12-14 15:34:10
Last Access Time:2019-12-14 15:35:13
四、源代碼地址
GitHub·地址
https://github.com/cicadasmile/java-base-parent
GitEE·地址
https://gitee.com/cicadasmile/java-base-parent