會話跟蹤技術允許服務器確定訪問站點的用戶、用戶訪問站點的次數和用戶停留站點的時間段
客戶端和服務器之間的會話ID和狀態資訊,通常有四種方法:
1.使用Servlet API中的Session會話機制(存盤在Web服務器)
①.當客戶端第一次請求會話物件時,服務器會創建一個 Session 物件,并為該 Session 物件分配一個唯一的 SessionID(用來標識這個 Session 物件),
②.服務器將 SessionID 以 Cookie(Cookie 名稱為:“JSESSIONID”,值為 SessionID 的值)的形式發送給客戶端瀏覽器,然后客戶端瀏覽器再次發送 HTTP 請求時,會將攜帶 SessionID 的 Cookie 隨請求一起發送給服務器,服務器從請求中讀取 SessionID,然后根據 SessionID 找到對應的 Session 物件,
③.Session 物件在如下 3 種情況下會被銷毀:
Session 過期;
呼叫 session.invalidate() 方法,手動銷毀 Session;
服務器關倍訓者應用被卸載,???????
//獲取session物件
HttpSession session=request.getSession();
//設定會話的過期時間
request.getSession().setMaxInactiveInterval(100);
2.使用Cookie (存盤在客戶端瀏覽器)
Cookie c1=new Cookie( "name" , name) ;
Cookie c2=new Cookie( "pwd", pwd);
//設定cookie得保存時間
c1.setMaxAge(60*60);
c2.setMaxAge(60*60);
//寫入cookie
response.addCookie(c1);
response.addCookie(c2);
request.getRequestDispatcher("sccuess.jsp").forward(request,response);
3.URL重寫:URL可以在后面附加引數,和服務器的請求一 起發送,這些引數為 名字/值 對
<%
HttpSession session1=request.getSession();
String url=request.getContextPath();
String newurl=response.encodeURL(url+"aa.jsp");
if(newur1.endswith(session1.getId())){
out . print ( "cookie被禁用,只能用url重寫得方式了");
out. print (newurl);
}else{
out. print ( "cookie沒有被禁用");out. print(newurl);
}
%>
4.隱藏表單域: <input type="hidden">,非常適合步需要大量資料存盤的會話應用
<form action="registerServlet" method = "post">
郵件地址:<input type="text" name = "email" ><br>
年齡:<input type="text" name = "age"><br>
<!一使用隱藏表單域來傳遞兩個資料-->
<input type="hidden" name="uname" value="張三">
<input type="hidden" name="pwd" value="123">
<input type= "submit" value="提交到服務器">
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396544.html
標籤:其他
