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); } }