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. bzoj 2482: [Spoj GSS2] Can you answer these queries II 线段树

    2482: [Spoj1557] Can you answer these queries II Time Limit: 20 Sec  Memory Limit: 128 MBSubmit: 145 ...

  2. [原博客] BZOJ 2725 : [Violet 6]故乡的梦

    这个题在bzoj上好像是个权限题,想做的可以去Vani的博客下载测试数据.这里有题面. 简单叙述一下题意:给你一个n个点.m条边的带权无向图,S点和T点,询问Q次删一条给定的边的S-T最短路. 其中  ...

  3. Tiny210v2( S5PV210 )平台下创建基本根文件系统

    转自Tiny210v2( S5PV210 )平台下创建基本根文件系统 0. 概要介绍 ========================================================= ...

  4. HANDLE HINSTANCE HWND CWnd CDC

    HANDLE HINSTANCE HWND CWnd CDC 句柄:   柄,把柄 例如一个锅的手柄,你只要抓住了它,你就可以很好地操作那个锅,不过很明显你只能通过锅的手柄来做一些诸如炒菜之类的事,你 ...

  5. VC自动与Internet时间服务器同步更新

    在VCKBASE.CSDN里挖了许久的坟,才找到一些有点用的资料,最后自己整理出这样的个函数,方面VC实现时间同步,多的不说,自己看源码,根据自己的需要可以适当修改源码: #include <W ...

  6. Android MediaPlayer状态机

    对播放音频/视频文件和流的控制是通过一个状态机来管理的.下图显示一个MediaPlayer对象被支持的播放控制操作驱动的生命周期和状态.椭圆代表MediaPlayer对象可能驻留的状态.弧线表示驱动M ...

  7. warning: push.default is unset;

    git push warning questions This warning was introduced in Git 1.7.11 along with the simple style of ...

  8. Hadoop RPC源码阅读-交互协议

    Hadoop版本Hadoop2.6 RPC主要分为3个部分:(1)交互协议(2)客户端 (3)服务端 (1)交互协议 协议:把某些接口和接口中的方法称为协议,客户端和服务端只要实现这些接口中的方法就可 ...

  9. clang failed with exit code 1 的常见情况

    1:文件重复,如生成了一份  xxx副本.m 2:reachablity.h 这个文件经常重复. 以上优先检查 .

  10. POJ 3107

    #include<iostream> #include<cstdio> #include<cstring> #include<string> #incl ...