Servlet的Cookie和HttpSession
1.會話概述
什么是會話?
如同打電話
會話解決的問題?
保持各個客戶端自己的數(shù)據(jù)
2.Cookie
1.Cookie的定義
2.Cookie的主要方法
注意以下幾點(diǎn)
name: 名稱不能唯一確定一個cookie。路徑可能不同
value: 不能存中文
path: 默認(rèn)是寫入cookie那個應(yīng)用的訪問路徑
如:http://localhost:8080/day10/servlet/cookieDemo1
Path: /day10/servlet/
當(dāng)客戶端訪問服務(wù)器其它資源時,根據(jù)訪問路徑來決定是否帶著cookie到服務(wù)器
當(dāng)訪問的路徑是以cookie中path開頭的路徑,就帶cookie,否則就不帶。
maxAge: cookie的保存時間。默認(rèn)是-1(表示保存在瀏覽器的內(nèi)存中)。單位是秒
負(fù)數(shù):cookie存在瀏覽器的內(nèi)存中。
0:刪除。路徑要保持一致,否則會刪錯了。
正數(shù):緩存(持久化到磁盤中)的時間。
Demo1Cookie設(shè)置最后訪問時間
?
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 //設(shè)置本次訪問時間到Cookie 11 //設(shè)置清除cookie 12 out.print("<a href='"+request.getContextPath()+"/servlet/CookieDemo2'>clear</a>"); 13 //得到當(dāng)前時間,創(chuàng)建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 //設(shè)置最大時間 18 lck.setMaxAge(60*5); 19 //設(shè)置可訪問的路徑 20 lck.setPath(request.getContextPath()); 21 //添加cookie到瀏覽器 22 response.addCookie(lck);?
清除Cookie的Servlet
清除Cookie其實(shí)就是設(shè)置Cookie的MaxAge為0,但是要注意:Path必須是和你要設(shè)置的Cookie相同,否則Cookie來自不同路徑同名屬于不同的Cookie
Cookie ck = new Cookie("lastAccessTime", "");//設(shè)置cookie存活時間 秒ck.setMaxAge(0);//設(shè)置cookie的路徑,決定哪些路徑會帶著這個cookie ck.setPath(request.getContextPath());//添加response.addCookie(ck);?
Demo2歷史記錄的案例
原理:
如圖,當(dāng)你瀏覽一本書的時候,還設(shè)置了一次Cookie,如果以前沒有歷史記錄,那么創(chuàng)建一個Cookie放歷史記錄,否則,修改原有Cookie,根據(jù)一定的規(guī)則,增加Cookie中id的排列規(guī)則(這里用'-'用作分隔符號讓字符串去切割).所有商品中的歷史信息會讀取響應(yīng)的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 //邏輯:獲取到發(fā)送過來的id,對它進(jìn)行處理成一個字符串以-連接代表歷史記錄的順序 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 //根據(jù)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再轉(zhuǎn)換成數(shù)組 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 }
中間的字符串處理部分可能有點(diǎn)復(fù)雜,可以優(yōu)化。但是也算完成了,沒有給Cookie加入過時的時間,所以瀏覽器關(guān)閉就被清理了。
?
3.HttpSession
1、HttpSession的定義
主要方法:
void setAttribute(String name,Object value); ? //設(shè)置Session的值
Object getAttribute(String name); ?//得到Session
void removeAttribute(String name); ?//刪除指定的值
HttpSession.getId(): ? //得到Id
setMaxInactiveInterval(int interval) ? ? //設(shè)置session的存活時間 秒
invalidate() 使此會話無效
2、為什么要學(xué)HttpSession?
> 它也是一個域?qū)ο? session ??servletContext ?request
> 同一個會話下,可以使一個應(yīng)用的多個資源共享數(shù)據(jù)
> cookie客戶端技術(shù),只能存字符串。HttpSession服務(wù)器端的技術(shù),它可以存對象。
?
3、Session的內(nèi)部執(zhí)行原理
HttpSession request.getSession():內(nèi)部執(zhí)行原理
1、獲取名稱為JSESSIONID的cookie的值。
2、沒有這樣的cookie,創(chuàng)建一個新的HttpSession對象,分配一個唯一的SessionID,并且向客戶端寫了一個名字為JSESSIONID=sessionID的cookie
3、有這樣的Cookie,獲取cookie的值(即HttpSession對象的值),從服務(wù)器的內(nèi)存中根據(jù)ID找那個HttpSession對象:
找到了:取出繼續(xù)為你服務(wù)。
找不到:從2開始。
?
4、Session的狀態(tài)
?
?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 ,創(chuàng)建一個map集合,保存這個session,Map<Book, Integer> books = (Map<Book, Integer>) request.getSession().getAttribute("books");//第一次為空所以如果是第一次那么就為null,表示這個書只有一本,那么新創(chuàng)建一個集合,放入這本書if(books == null) {books = new HashMap<Book, Integer>();books.put(book, 1);}else {//如果不是第一次且已經(jīng)包含這本書了,那么就使這本書的value+1if(books.containsKey(book)){books.put(book, books.get(book)+1);}else {//否則,放入這1個這本書就行books.put(book, 1);}}//將books這個map集合放入sessionsession.setAttribute("books", books);}沒有設(shè)置Session的過期時間,可以自己設(shè)置,在上面的有兩種設(shè)置方法.
?
6、用戶禁用了Cookie的解決辦法
解決方案:
方案一:在主頁上給出提示:請不要禁用您的cookie
方案二:URL重寫。必須對網(wǎng)站的所有地址都重寫。
http://url--->http://url;JSESSIONID=111
response.encodeURL(String url);
看瀏覽器有沒有發(fā)送cookie請求消息頭,沒有就重寫URL,有就不重寫。
request.getSession();必須寫
轉(zhuǎn)載于:https://www.cnblogs.com/fangqiangblog/p/7478128.html
總結(jié)
以上是生活随笔為你收集整理的Servlet的Cookie和HttpSession的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: skill alpha protocol
- 下一篇: 大数据销售管理服务提供商InsideSa