JSESSIONID設置在Cookie頭中攜帶過去,服務器根據這個sessionID獲取對應的Session,而不是從新建立一個新Session(除了這個Session失效)。html
以java.net.HttpURLConnection發起請求爲例:java
獲取Cookie: web
URL url = new URL(requrl);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
// 取得sessionid.
String cookieval = con.getHeaderField("set-cookie");
String sessionid;
if(cookieval != null) {
sessionid = cookieval.substring(0, cookieval.indexOf(";"));
}服務器
//sessionid值格式:JSESSIONID=AD5F5C9EEB16C71EC3725DBF209F6178,是鍵值對,不是單指值cookie
發送設置cookie: session
URL url = new URL(requrl);
HttpURLConnectioncon= (HttpURLConnection) url.openConnection();
if(sessionid != null) {
con.setRequestProperty("cookie", sessionid);
}ui
只要設置了sessionID,這樣web服務器在接受請求的時候就會自動搜索對應的session了,從而保證了在同一會話Session。url