日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Servlet的Cookie和HttpSession

發布時間:2025/3/21 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Servlet的Cookie和HttpSession 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.會話概述

  什么是會話?

  如同打電話

  會話解決的問題?

  保持各個客戶端自己的數據

2.Cookie

   1.Cookie的定義

  

  2.Cookie的主要方法

注意以下幾點

  name: 名稱不能唯一確定一個cookie。路徑可能不同

  value: 不能存中文

  path: 默認是寫入cookie那個應用的訪問路徑

  如:http://localhost:8080/day10/servlet/cookieDemo1

  Path: /day10/servlet/

  當客戶端訪問服務器其它資源時,根據訪問路徑來決定是否帶著cookie到服務器

  當訪問的路徑是以cookiepath開頭的路徑,就帶cookie,否則就不帶。

  maxAge: cookie的保存時間。默認是-1(表示保存在瀏覽器的內存中)。單位是秒

    負數:cookie存在瀏覽器的內存中。

    0:刪除。路徑要保持一致,否則會刪錯了。

    正數:緩存(持久化到磁盤中)的時間。

Demo1Cookie設置最后訪問時間 

?

1 response.setContentType("text/html; charset = UTF-8"); 2 PrintWriter out = response.getWriter(); 3 //得到Cookie,輸出上次的訪問時間,第一次訪問是沒有的 4 Cookie[] cookies = request.getCookies(); 5 for (int i = 0; cookies != null && i < cookies.length; i++) { 6 if(cookies[i].getName().equals("lastAccessTime")){ 7 out.write("你最后的訪問時間為"+cookies[i].getValue()); 8 } 9 } 10 //設置本次訪問時間到Cookie 11 //設置清除cookie 12 out.print("<a href='"+request.getContextPath()+"/servlet/CookieDemo2'>clear</a>"); 13 //得到當前時間,創建cookie 14 SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); 15 String time = sdf.format(new Date()); 16 Cookie lck = new Cookie("lastAccessTime", time); 17 //設置最大時間 18 lck.setMaxAge(60*5); 19 //設置可訪問的路徑 20 lck.setPath(request.getContextPath()); 21 //添加cookie到瀏覽器 22 response.addCookie(lck);

?

清除Cookie的Servlet

清除Cookie其實就是設置Cookie的MaxAge為0,但是要注意:Path必須是和你要設置的Cookie相同,否則Cookie來自不同路徑同名屬于不同的Cookie

Cookie ck = new Cookie("lastAccessTime", "");//設置cookie存活時間 秒ck.setMaxAge(0);//設置cookie的路徑,決定哪些路徑會帶著這個cookie ck.setPath(request.getContextPath());//添加response.addCookie(ck);

?

Demo2歷史記錄的案例

原理:

如圖,當你瀏覽一本書的時候,還設置了一次Cookie,如果以前沒有歷史記錄,那么創建一個Cookie放歷史記錄,否則,修改原有Cookie,根據一定的規則,增加Cookie中id的排列規則(這里用'-'用作分隔符號讓字符串去切割).所有商品中的歷史信息會讀取響應的Cookie,如果有,那么讀取到,切割id,遍歷,查詢,輸出書名字。

原理大概如此上代碼:

  ShowAllBooks:

  

1 response.setContentType("text/html; charset=UTF-8"); 2 PrintWriter out = response.getWriter(); 3 Map<String, Book> map = Utils.getAllBook(); 4 out.write("所有的書<br/>"); 5 //遍歷map 6 for (Map.Entry<String, Book> book : map.entrySet()) { 7 out.write("<a href='"+request.getContextPath()+"/servlet/BookDetails?id="+book.getKey()+"',target='blank'>"+book.getValue().getName()+"</a><br>"); 8 } 9 out.write("瀏覽歷史<br/>"); 10 //遍歷cookie 11 Cookie[] cookies = request.getCookies(); 12 for (int i = 0; cookies!=null && i < cookies.length; i++) { 13 if(cookies[i].getName().equals("history")) { 14 String[] s = cookies[i].getValue().split("-"); 15 for (int j = s.length; j >= 0 ; j--) { 16 out.write(Utils.getMapById(s[j]).getName()+"<br/>"); 17 } 18 } 19 }

ShowBooksDetail:

  

1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 //邏輯:獲取到發送過來的id,對它進行處理成一個字符串以-連接代表歷史記錄的順序 4 response.setContentType("text/html; charset=UTF-8"); 5 PrintWriter out = response.getWriter(); 6 String id = request.getParameter("id"); 7 out.write(Utils.getMapById(id).toString()); 8 Cookie history = new Cookie("history", getCookie(request, id)); 9 response.addCookie(history); 10 } 11 //根據id和request來獲取 12 public String getCookie(HttpServletRequest request, String id) { 13 Cookie[] cookies = request.getCookies(); 14 if(cookies == null) { 15 return id; 16 } 17 18 String s = null; 19 // 裝入字符串 20 for (int i = 0; i < cookies.length; i++) { 21 if(cookies[i].getName().equals("history")){ 22 s = cookies[i].getValue(); 23 } 24 } 25 26 if(s == null){ 27 return id; 28 } 29 //分解 30 String[] arr = s.split("-"); 31 //裝入list 32 List<String> list = new ArrayList<String>(Arrays.asList(arr)); 33 //如果包含id,那么移除 34 if(s.contains(id)){ 35 list.remove(id); 36 } else { 37 if(list.size()<3) { 38 39 } else { 40 list.remove(0); 41 } 42 } 43 list.add(id); 44 //最后裝入StringBuffer再轉換成數組 45 StringBuffer sb = new StringBuffer(); 46 for (int i = 0; i < list.size(); i++) { 47 if(i>0) { 48 sb.append("-"); 49 } 50 sb.append(list.get(i)); 51 } 52 53 return sb.toString(); 54 }

中間的字符串處理部分可能有點復雜,可以優化。但是也算完成了,沒有給Cookie加入過時的時間,所以瀏覽器關閉就被清理了。

?

3.HttpSession

1、HttpSession的定義

  

  主要方法:

  void setAttribute(String name,Object value);    ? //設置Session的值

  Object getAttribute(String name);         ?//得到Session

  void removeAttribute(String name);        ?//刪除指定的值

  HttpSession.getId():               ? //得到Id

  setMaxInactiveInterval(int interval) ?       ? //設置session的存活時間 秒   

  invalidate() 使此會話無效   

         

2、為什么要學HttpSession?

> 它也是一個域對象: session ??servletContext ?request

> 同一個會話下,可以使一個應用的多個資源共享數據

> cookie客戶端技術,只能存字符串。HttpSession服務器端的技術,它可以存對象

?

3、Session的內部執行原理

HttpSession request.getSession():內部執行原理

1、獲取名稱為JSESSIONID的cookie的值。

2、沒有這樣的cookie,創建一個新的HttpSession對象,分配一個唯一的SessionID,并且向客戶端寫了一個名字為JSESSIONID=sessionID的cookie

3、有這樣的Cookie,獲取cookie的值(即HttpSession對象的值),從服務器的內存中根據ID找那個HttpSession對象:

找到了:取出繼續為你服務。

找不到:從2開始。

?

4、Session的狀態

?

?5、Demo1簡單的購物車

?

Servlet1:首頁

1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 response.setContentType("text/html; charset=UTF-8"); 4 PrintWriter out = response.getWriter(); 5 6 out.write("選擇你要購買的<br/>"); 7 //遍歷到所有的書 8 Map<String, Book> allBook = Utils.getAllBook(); 9 for (Entry<String, Book> book : allBook.entrySet()) { 10 out.write("<a href='" + request.getContextPath() 11 + "/servlet/addBook?id="+book.getKey()+"' target='_blank'>" 12 + book.getValue().getName() + "<a/><br/>"); 13 } 14 out.write("<a href='/day10_01_session/servlet/ShowCart' target='_blank'>查看cart</a>"); 15 }

?

Servlet2:購物車頁面

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html; charset=UTF-8");PrintWriter out = response.getWriter();Map<Book,Integer> books = (Map<Book, Integer>) request.getSession().getAttribute("books");//如果session為空說明沒有買書if(books == null) {out.write("你還沒有購買書籍");return;}//否則遍歷這個集合,取出book對象遍歷輸出for (Entry<Book,Integer> book : books.entrySet()) {out.write(book.getKey().getName()+"num: "+book.getValue().toString());}}

?

Servlet3:買書頁面(詳情頁面)

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String id = request.getParameter("id");Book book = Utils.getMapById(id);HttpSession session = request.getSession();//得到Session ,創建一個map集合,保存這個session,Map<Book, Integer> books = (Map<Book, Integer>) request.getSession().getAttribute("books");//第一次為空所以如果是第一次那么就為null,表示這個書只有一本,那么新創建一個集合,放入這本書if(books == null) {books = new HashMap<Book, Integer>();books.put(book, 1);}else {//如果不是第一次且已經包含這本書了,那么就使這本書的value+1if(books.containsKey(book)){books.put(book, books.get(book)+1);}else {//否則,放入這1個這本書就行books.put(book, 1);}}//將books這個map集合放入sessionsession.setAttribute("books", books);}

沒有設置Session的過期時間,可以自己設置,在上面的有兩種設置方法. 

?

6、用戶禁用了Cookie的解決辦法

解決方案:

方案一:在主頁上給出提示:請不要禁用您的cookie

方案二:URL重寫。必須對網站的所有地址都重寫。

http://url--->http://url;JSESSIONID=111

response.encodeURL(String url);

看瀏覽器有沒有發送cookie請求消息頭,沒有就重寫URL,有就不重寫。

request.getSession();必須寫

轉載于:https://www.cnblogs.com/fangqiangblog/p/7478128.html

總結

以上是生活随笔為你收集整理的Servlet的Cookie和HttpSession的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。