方立勋_30天掌握JavaWeb_Cookie
會話技術介紹
什么是會話?
- 會話可簡單理解為:用戶開一個瀏覽器,點擊多個超鏈接,訪問服務器多個web資源,然后關閉瀏覽器,整個過程稱之為一個會話。
會話過程中要解決的一些問題?
- 每個用戶在使用瀏覽器與服務器進行會話的過程中,不可避免各自會產生一些數據,程序要想辦法為每個用戶保存這些數據。
- 例如:用戶點擊超鏈接通過一個servlet購買了一個商品,程序應該想辦法保存用戶購買的商品,以便于用戶點結帳servlet時,結帳servlet可以得到用戶購買的商品為用戶結帳。
- 思考:用戶購買的商品保存在request或servletContext中行不行?
1. Cookie
Cookie是客戶端技術,程序把每個用戶的數據以cookie的形式寫給用戶各自的瀏覽器。當用戶使用瀏覽器再去訪問服務器中的web資源時,就會帶著各自的數據去。這樣,web資源處理的就是用戶各自的數據了。
2. Session
Session是服務器端技術,利用這個技術,服務器在運行時可以為每一個用戶的瀏覽器創建一個其獨享的session對象,由于session為用戶瀏覽器獨享,所以用戶在訪問服務器的web資源時,可以把各自的數據放在各自的session中,當用戶再去訪問服務器中的其它web資源時,其它web資源再從用戶各自的session中取出數據為用戶服務。
Cookie
Cookie API:
javax.servlet.http.Cookie類用于創建一個Cookie,response接口也中定義了一個addCookie方法,它用于在其響應頭中增加一個相應的Set-Cookie頭字段。 同樣,request接口中也定義了一個getCookies方法,它用于獲取客戶端提交的Cookie。Cookie類的方法:
public Cookie(String name,String value)
setValue與getValue方法
setMaxAge與getMaxAge方法
setPath與getPath方法 /day06
setDomain與getDomain方法
getName方法
Cookie應用
顯示用戶上次訪問網站的時間
import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //代表網站首頁 //Cookie技術顯示用戶上次訪問網站的時間 public class CookieDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("<a href='/day07/servlet/CookieDemo2'>清除上次訪問時間</a><br>"); out.print("您上次訪問的時間是:"); // 拿到請求頭中所有的cookie Cookie cookies[] = request.getCookies(); // 遍歷cookies找到lastAccessTime這個cookie for (int i = 0; cookies != null && i < cookies.length; i++) { if (cookies[i].getName().equals("lastAccessTime")) { // 得到最后訪問時間的毫秒數 long cookieValue = Long.parseLong(cookies[i].getValue()); // 將最后訪問時間變成一個日期類型 Date date = new Date(cookieValue); // 格式化這個日期 DateFormat df = new SimpleDateFormat("yyyy-MM-WW kk:mm:ss"); String lastAccessTime = df.format(date); out.print(lastAccessTime); } } // 將最新的訪問時間設置回去 Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis() + ""); // 設置有效期為一個月 cookie.setMaxAge(1 * 3600 * 24 * 30); // 設置有效訪問路徑為/day07這個項目下的所有資源 cookie.setPath("/day07"); // 在response中增加一個cookie,服務器會自動增加Set-Cookie頭字段 response.addCookie(cookie); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //刪除瀏覽器中的cookie public class CookieDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { test1(response); test2(request, response); } // 自己實驗的方法,拿到了原有的cookie想要刪除還是要先設置下Path,否則Path還是會在這個servlet的目錄下 // 拿到了原有的cookie,如果只修改setMaxAge為0還是不行的! private void test2(HttpServletRequest request, HttpServletResponse response) { // 拿到請求頭中所有的cookie Cookie cookies[] = request.getCookies(); // 遍歷cookies找到lastAccessTime這個cookie for (int i = 0; cookies != null && i < cookies.length; i++) { if (cookies[i].getName().equals("lastAccessTime")) { Cookie cookie = cookies[i]; cookie.setMaxAge(0); cookie.setPath("/day07"); response.addCookie(cookie); } } } // 開發中的方法 private void test1(HttpServletResponse response) { Cookie cookie = new Cookie("lastAccessTime", ""); // 設置為0表示讓瀏覽器刪除這個cookie cookie.setMaxAge(0); // 刪除cookie的時候Path必須一致,因為同一個cookie,Path肯定一致 cookie.setPath("/day07"); response.addCookie(cookie); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }Cookie細節
- 一個Cookie只能標識一種信息,它至少含有一個標識該信息的名稱(NAME)和設置值(VALUE)。
- 一個WEB站點可以給一個WEB瀏覽器發送多個Cookie,一個WEB瀏覽器也可以存儲多個WEB站點提供的Cookie。
- 瀏覽器一般只允許存放300個Cookie,每個站點最多存放20個Cookie,每個Cookie的大小限制為4KB。
- 如果創建了一個cookie,并將他發送到瀏覽器,默認情況下它是一個會話級別的cookie(即存儲在瀏覽器的內存中),用戶退出瀏覽器之后即被刪除。若希望瀏覽器將該cookie存儲在磁盤上,則需要使用maxAge,并給出一個以秒為單位的時間。將最大時效設為0則是命令瀏覽器刪除該cookie。
- 注意,刪除cookie時,path必須一致,否則不會刪除
Cookie顯示商品的瀏覽記錄
import java.io.IOException; import java.io.PrintWriter; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //代表首頁的servlet public class CookieDemo3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.顯示網站的所有商品 response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("本網站有如下商品:<br/>"); Map<String, Book> map = Db.getAll(); // 遍歷存有數據信息的“數據庫”顯示到頁面中 for (Map.Entry<String, Book> entry : map.entrySet()) { Book book = entry.getValue(); // 點擊超鏈接后,在新的頁面打開target="_blank" out.print("<a href='/day07/servlet/CookieDemo4?id=" + book.getId() + "' target='_blank'>" + book.getName() + "</a><br/>"); } // 2.顯示用戶曾經看過的商品 out.print("<br/>您曾經看過如下商品:</br>"); // 拿到請求中所有的Cookie Cookie cookies[] = request.getCookies(); // 遍歷Cookie,看看有沒有瀏覽商品的Cookie for (int i = 0; cookies != null && i < cookies.length; i++) { // 如果有瀏覽商品的Cookie則拿到其中的商品,瀏覽過的商品是很多件的,商品是以,分割的 if (cookies[i].getName().equals("bookHistory")) { // 分割字符串,拿到留有瀏覽過的商品的id // 不管,有沒有在正則表達式中定義,都以,分割 String[] ids = cookies[i].getValue().split("\\,"); // 2,3,1 // 遍歷所有商品id獲得商品 for (String id : ids) { Book book = Db.getAll().get(id); out.print(book.getName() + "<br />"); } } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } // 模擬數據庫,從這個類中提取書的信息 class Db { // 實際開發中存儲數據的集合有檢索數據的需求,都用雙列的(map),如果沒有檢索數據需求,用單列的(list、set) // LinkedHashMap是有序存儲 private static Map<String, Book> map = new LinkedHashMap<String, Book>(); // 對書進行靜態初始化 static { // key是商品的id,value是商品,商品中也是有商品的id的 map.put("1", new Book("1", "javaweb開發", "老張", "一本好書!")); map.put("2", new Book("2", "jdbc開發", "老張", "一本好書!")); map.put("3", new Book("3", "spring開發", "老黎", "一本好書!")); map.put("4", new Book("4", "struts開發", "老畢", "一本好書!")); map.put("5", new Book("5", "android開發", "老黎", "一本好書!")); } public static Map<String, Book> getAll() { return map; } } // 模擬書類 class Book { private String id; private String name; private String author; private String description; public Book() { super(); } public Book(String id, String name, String author, String description) { super(); this.id = id; this.name = name; this.author = author; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.LinkedList; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //顯示商品詳細信息的servlet public class CookieDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.根據用戶帶過來的id,顯示相應商品的詳細信息 response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); // 獲取瀏覽的書的id String id = request.getParameter("id"); // 根據id拿到書的信息 Book book = Db.getAll().get(id); out.print(book.getId() + "<br/>"); out.print(book.getAuthor() + "<br/>"); out.print(book.getName() + "<br/>"); out.print(book.getDescription() + "<br/>"); // 2.構建Cookie,回寫給瀏覽器 String cookieValue = buildCookie(id, request); Cookie cookie = new Cookie("bookHistory", cookieValue); cookie.setMaxAge(1 * 3600 * 24 * 30); cookie.setPath("/day07"); response.addCookie(cookie); } // 構建Cookie的方法 private String buildCookie(String id, HttpServletRequest request) { // 1.用戶沒有帶Cookie過來 bookHistory=null id=1 return 1 // 2.用戶帶Cookie過來 bookHistory=2,5,1 id=1 bookHistory中包含id // 要把2,5,1中的1刪掉加在最前面 return1,2,5 // 3.用戶帶Cookie過來 bookHistory=2,5,4 id=1 假設列表最大顯示3個Cookie return1,2,5 // 4.用戶帶Cookie過來 bookHistory=2,5 id=1 并且列表沒有超出范圍 return 1,2,5 // 先把要Cookie的值創建出來 String bookHistory = null; // 得到Cookie,看看有沒有bookHistory這個Cookie,有的話,把它的值賦給bookHistory(要返回的String類型的) Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { if (cookies[i].getName().equals("bookHistory")) { bookHistory = cookies[i].getValue(); } } // 第一種可能,那么返回的就是瀏覽的這個商品的id if (bookHistory == null) { return id; } // 第二種可能,要判斷有沒有包含,要先轉成List,調用List的方法判斷String.content判斷出來的數據是有錯誤的,判斷1的話21也包含 // 由于增刪改查操作較多,所以用鏈表 LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory .split("\\,"))); /* * if(list.contains(id)) { list.remove(id); list.addFirst(id); } else { * //第三種和第四種可能 //第三種可能 if(list.size()>=3) { list.removeLast(); * list.addFirst(id); } else { //第四種可能 list.addFirst(id); } } */ // 上面的代碼優化,不管怎么樣都要list.addFirst(id); if (list.contains(id)) { list.remove(id); } else { if (list.size() >= 3) { list.removeLast(); } } list.addFirst(id); // 將list中的數據構建字符串返回 StringBuffer sb = new StringBuffer(); for (String bid : list) { sb.append(bid + ","); } return sb.deleteCharAt(sb.length() - 1).toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }Cookie常見應用:顯示上次訪問網站的時間、顯示瀏覽過的商品、做購物(購物車)、自動登錄(Cookie把用戶的用戶名和密碼回寫給瀏覽器,但是寫這個程序的時候用戶名是直接回寫的,密碼是通過加密后回寫的)
總結
以上是生活随笔為你收集整理的方立勋_30天掌握JavaWeb_Cookie的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 方立勋_30天掌握JavaWeb_req
- 下一篇: Tomcat version 7.0 o