cookie記錄瀏覽記錄
HashMap也是我們使用非常多的Collection,它是基於哈希表的 Map 接口的實現,以key-value的形式存在。在HashMap中,key-value總是會當做一個整體來處理,系統會根據hash算法來來計算key-value的存儲位置,我們總是可以通過key快速地存、取value。下面就來分析HashMap的存取。
javabean.java
定義Book類的五個屬性
package Book.bean; public class Book { private String id; private String bookName; private String author; private float price; private String description; //帶參數的構造函數 public Book(String id, String bookName, String author, float price, String description) { this.id = id; this.bookName = bookName; this.author = author; this.price = price; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Book [id=" + id + ", bookName=" + bookName + ", author=" + author + ", price=" + price + ", description=" + description + "]"; } }
BookUtils.java
存取書的內容,利用hashMap來存取數據
package Book.utils; import java.util.HashMap; import java.util.Map; import Book.bean.Book; //書放到數據庫中的實現類 public class BookUtils { //為了方便,創建一個靜態的Map private static Map<String,Book> map = new HashMap<String,Book>(); //靜態塊 static{ map.put("1", new Book("1","降龍十1掌","金庸1",1,"武功絕學降龍十1掌")); map.put("2", new Book("1","降龍十2掌","金庸2",2,"武功絕學降龍十2掌")); map.put("3", new Book("1","降龍十3掌","金庸3",3,"武功絕學降龍十3掌")); map.put("4", new Book("1","降龍十4掌","金庸4",4,"武功絕學降龍十4掌")); map.put("5", new Book("1","降龍十5掌","金庸5",5,"武功絕學降龍十5掌")); map.put("6", new Book("1","降龍十6掌","金庸6",6,"武功絕學降龍十6掌")); map.put("7", new Book("1","降龍十7掌","金庸7",7,"武功絕學降龍十7掌")); map.put("8", new Book("1","降龍十8掌","金庸8",8,"武功絕學降龍十8掌")); map.put("9", new Book("1","降龍十9掌","金庸9",9,"武功絕學降龍十9掌")); map.put("10", new Book("1","降龍十掌","金庸10",10,"武功絕學降龍十掌")); map.put("11", new Book("1","降龍十1掌","金庸11",11,"武功絕學降龍十1掌")); } //拿取書 public static Map<String,Book> getAllBook(){ return map; } //獲取一本書 public static Book getBookById(String id){ return map.get(id); } }
showAllBook.java
讀取並顯示書籍信息
package Book.servlet; import java.io.IOException; import java.io.PrintWriter; 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; import Book.bean.Book; import Book.utils.BookUtils; public class showAllBook extends HttpServlet { /** * 1.顯示所有的書 * 2.顯示瀏覽的歷史記錄 * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write("書架:<br>"); //1.顯示所有的書 Map<String,Book> map = BookUtils.getAllBook(); //遍歷集合 foreach for (Map.Entry<String, Book> entry : map.entrySet()) { //拿到每一本書的id String id = entry.getKey(); //拿到每一本書 Book book = entry.getValue(); //output book name //客戶端跳轉 out.write(book.getBookName() + " <a href='" + request.getContextPath() + "/servlet/ShowDetail?id=" + id + " '>顯示詳細信息</a><br>"); } out.write("<br><br><br>"); //顯示瀏覽的歷史記錄:cookie的名字定義為history : 值的形式:1-2-3 //拿到cookie, Cookie[] cs = request.getCookies(); //for for (int i = 0; cs != null && i < cs.length; i++) { Cookie c = cs[i]; if("history".equals(c.getName())){ //show out.write("你的瀏覽記錄:<br>"); //got cookie String value = c.getValue(); //根據形式來拆分成數組 String [] ids = value.split("-"); //show the book for (int j = 0; j < ids.length; j++) { Book b = BookUtils.getBookById(ids[j]); out.write(b.getBookName() + "<br>"); } } } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
ShowDetail.java
1.顯示書的詳細信息: 獲取傳遞過來的 id ,通過BookUtils來獲取書的全部信息
2.顯示瀏覽記錄 : 獲取傳遞過來的cookie,分析處理cookie
package Book.servlet; 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; import Book.bean.Book; import Book.utils.BookUtils; /** * 1.顯示書的詳細信息 * 2.發送歷史瀏覽記錄 * @author kj * */ public class ShowDetail extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //1.拿到傳遞的數據 String id = request.getParameter("id"); //根據id查詢書 Book book = BookUtils.getBookById(id); //顯示書的信息 out.write(book + " <a href='" + request.getContextPath() + "/servlet/showAllBook'>返回主頁繼續瀏覽</a><br>"); //2.發送cookie //獲取歷史記錄字符串 String history = getHistory(request,id); //創建cookie Cookie c = new Cookie("history",history); c.setMaxAge(Integer.MAX_VALUE); //設置Cookie存放路徑 c.setPath(request.getContextPath()); response.addCookie(c); } /** * 獲取要發往客戶端的歷史記錄的字符串 * @return */ private String getHistory(HttpServletRequest request, String id) { // 獲取字符串的情況 /** * 歷史記錄的的cookie被獲取 點擊的書 結果 * 1. null n n * 2. 1 1 1 * 3. 1 2 2-1 * 4 1-2 1 1-2 * 5. 1-2 2 2-1 * 6. 1-2 3 3-1-2 * 7. 1-2-3 1 1-2-3 * 8. 1-2-3 2 2-1-3 * 9. 1-2-3 3 3-1-2 * 10 1-2-3 4 4-1-2 */ //設定一個cookie為空,用來存放獲取到的原來的cookie Cookie history = null; //拿到所有的cookie Cookie[] cs = request.getCookies(); //循環判斷所有的cookie for (int i = 0; cs!=null && i < cs.length; i++) { if(cs[i].getName().equals("history")){ history = cs[i]; break; } } //情況1,history為空,沒有,就把id添加進去 if(history == null) return id; //如果不為空 String value = history.getValue(); System.out.println("----value的長度-----" + value.length()+"***value的值***"+ value); if(value.length() == 1 ){ //2,3的情況 if(value.equals(id)){ //第一種情況 return id; }else{ return id + "-" + value; } } //剩下的就是大於1的情況了,說明有兩個或兩個以上的,這就需要拆封成單個字符串了 String[] ids = value.split("-"); ////Arrays.asList 返回一個受指定數組支持的固定大小的列表,也可以用for循環 LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids)); //返回此列表中首次出現的指定元素的索引,如果此列表 中不包含該元素,則返回 -1 int index = list.indexOf(id); //4,5,6的情況 // value的值包括 “a” “-” “b” 所以是3 if(value.length() == 3){ System.out.println("######進入 value=3 的情況######"); if(index == -1){ //說明沒有點擊過 list.addFirst(id); }else{ //說明是點擊過的書 list.remove(index); list.add(id); } } //7,8,9,10的情況,都是三個數 if(value.length() > 3){ System.out.println("@@@@@@@進入 value>3 的情況@@@@@@@"); if(index == -1 ){ list.removeLast(); list.addFirst(id); }else{ list.remove(index); list.addFirst(id); } } //處理完成后需要將數據輸出成字符串的形式 StringBuffer sb = new StringBuffer(list.get(0)); for (int j = 1; j < list.size(); j++) { sb.append("-" + list.get(j)); } return sb.toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); doGet(request, response); } }