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("", new Book("","降龙十1掌","金庸1",,"武功绝学降龙十1掌"));
map.put("", new Book("","降龙十2掌","金庸2",,"武功绝学降龙十2掌"));
map.put("", new Book("","降龙十3掌","金庸3",,"武功绝学降龙十3掌"));
map.put("", new Book("","降龙十4掌","金庸4",,"武功绝学降龙十4掌"));
map.put("", new Book("","降龙十5掌","金庸5",,"武功绝学降龙十5掌"));
map.put("", new Book("","降龙十6掌","金庸6",,"武功绝学降龙十6掌"));
map.put("", new Book("","降龙十7掌","金庸7",,"武功绝学降龙十7掌"));
map.put("", new Book("","降龙十8掌","金庸8",,"武功绝学降龙十8掌"));
map.put("", new Book("","降龙十9掌","金庸9",,"武功绝学降龙十9掌"));
map.put("", new Book("","降龙十掌","金庸10",,"武功绝学降龙十掌"));
map.put("", new Book("","降龙十1掌","金庸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() + "&nbsp;<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 = ; 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 = ; 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 + "&nbsp;&nbsp;<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 = ; 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() == ){
//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() == ){
System.out.println("######进入 value=3 的情况######");
if(index == -){
//说明没有点击过
list.addFirst(id);
}else{
//说明是点击过的书
list.remove(index);
list.add(id);
}
}
//7,8,9,10的情况,都是三个数
if(value.length() > ){
System.out.println("@@@@@@@进入 value>3 的情况@@@@@@@");
if(index == - ){
list.removeLast();
list.addFirst(id);
}else{
list.remove(index);
list.addFirst(id);
}
} //处理完成后需要将数据输出成字符串的形式
StringBuffer sb = new StringBuffer(list.get());
for (int j = ; 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);
}
}

cookie记录浏览记录的更多相关文章

  1. 简单的Cookie记录浏览记录案例

    books.jsp 界面 代码 <%@ page contentType="text/html;charset=UTF-8" language="java" ...

  2. Cookie 简单使用记录浏览记录

    ItemsDAO.java package dao; import java.util.* ; import java.sql.* ; import util.DBHelper; import ent ...

  3. jquery.cookie.js结合asp.net实现最近浏览记录

    一.html代码 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://ww ...

  4. Cookie实现商品浏览记录--方式二:JS实现

    使用Cookie实现商品浏览记录:方式二:JS方法实现cookie的获取以及写入.当某一个产品被点击时,触发JS方法.利用JS方法判断一下,此产品是否在浏览记录中.如果不存在,则将产品ID加入到coo ...

  5. 使用cookie实现打印浏览记录的功能

    可以用cookie知识来实现打印浏览记录.这里面用到的思路是将浏览记录以字符串的方式保存到cookie中,当浏览记录增加时,再将其转化为数组. $uri=$_SERVER['REQUEST_URI'] ...

  6. (JS实现顾客商品浏览记录以及购物车)Cookie的保存与删除

    //JS实现顾客浏览商品的记录以及实现购物车的功能function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.s ...

  7. 使用Cookie保存商品浏览记录

    数据流程:页面上是商品列表,点击<a href="productServlet">商品名</a> ==>跳转到自定义的servlet中进行处理,先得到 ...

  8. Cookie中图片的浏览记录与cookie读取servle时路径的设置(文字描述)

    public class ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpSer ...

  9. js操作Cookie,实现历史浏览记录

    /** * history_teacher.jsp中的js,最近浏览名师 * @version: 1.0 * @author: mingming */ $(function(){ getHistory ...

随机推荐

  1. Codeforces Round #197 (Div. 2) : E

    看了codeforces上的大神写的题解之后,才知道这道题水的根本! 不过相对前面两题来说,这道题的思维要难一点: 不过想到了水的根本,这题也真心不难: 方法嘛,就像剥洋葱一样,从外面往里面剥: 所以 ...

  2. easyui的datagrid组件,如何设置点击某行不会高亮该行的方式

    easyui的datagrid组件,有些时候我们点击某行不想高亮显示,如何设置点击某行不会高亮该行的方式,有好几种方法可以实现,我举几个,可以根据你具体需求灵活应用: 1.修改easyui的css将高 ...

  3. 单位有b\B\K\M\G的相互转换

    计算机存储计量单位 1. 计算机最小存储计量单位是:BIT(位) 2. 计算机最基本存储计量单位是:Bytes(字节) 3. Bit和Bytes的关系:8Bit=1Bytes 4. 其他常用单位:1K ...

  4. 李洪强iOS开发之-Swift_00_介绍

    SWIFT (计算机编程语言) Swift,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序. ...

  5. 在VS2008中配置WDK7600驱动开发环境

    网上这类资料多如牛毛,也许很多人都是转来转去,却很有人去真正的测试,有时候感觉确实对他人也是一种误导. 这里是我自己在VS2008 + WDK7600.16385.0 + DDKWizard配置自己的 ...

  6. git tag的使用

    查看所有的标签git tag 删除某一个标签git tag -d tagName 创建带注释的标签 git tag -a tagName -m "annotate" 轻量级标签 g ...

  7. 关于O(n)算法

    首先要明确一点,当数据规模达到百万时需用O(n)算法 如何实现O(n)算法,其实是对原有算法的一种改进 后者说是 原有算法+一点小性质=O(n)算法 下面我将举几个例子来说明这一点: 1.后缀数组中h ...

  8. 备份及还原Xcode的模拟器

    http://blog.csdn.net/it_magician/article/details/8749876 每次更新或者重装Xcode之后,最麻烦的莫过于各个模拟器的安装了,因为下载速度实在让人 ...

  9. HDU-1540          Tunnel Warfare

    Tunnel Warfare Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)To ...

  10. Git报错:insufficient permission for adding an object to repository database .git/objects

    在本地搭建Git服务器后,在开发机上push新代码,发现Git提示: insufficient permission for adding an object to repository databa ...