JavaWeb -- Cookie应用实例 -- 购物历史记录
1.
页面一:主页面 页面二: 详细显示页面
Demo2 负责页面一, 显示商品清单和历史记录
Demo3负责页面二,显示商品详细内容 和 写入相应的Cookie
SevletDemo2 代码:
package com.kevin; import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo2
*/
@WebServlet("/Demo2")
public class Demo2 extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public Demo2() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); //1.display all commodity
out.write("本网站所有商品如下:<br/>");
Map<String, Book> map = Db.getAll();
for(Map.Entry<String, Book> entry : map.entrySet())
{
Book book = entry.getValue();
out.print("<a href='/WebTest3/Demo3?id="+ book.getId()
+"' target='_blank'>"+ book.getName() +"</a>" + "<br/>");
} //2.display book history
out.print("曾经看过的商品:<br/>");
Cookie[] cookies = request.getCookies();
for( int i=0; cookies!=null && i<cookies.length; i++ )
{
if( cookies[i].getName().equals("bookHistory") )
{
String[] ids = cookies[i].getValue().split("\\,");
for(String id : ids)
{
//System.out.println("id=" + id);
Book book = (Book) Db.getAll().get(id);
out.print(book.getName() + "<br/>");
}
}
}
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} } class Db
{
private static Map<String, Book> map = new LinkedHashMap<String, Book>();
static
{
map.put("1", new Book("1", "JavaWeb", "zhangsan", "a good book"));
map.put("2", new Book("2", "Jdbc", "lisi", "a good book"));
map.put("3", new Book("3", "Spring", "wangwu", "a good book"));
map.put("4", new Book("4", "Struts", "zhaoliu", "a good book"));
map.put("5", new Book("5", "Android", "zhangfa", "a good book"));
} public static Map getAll()
{
return map;
} } class Book
{
private String id;
private String name;
private String author;
private String description; public Book() {
super();
// TODO Auto-generated constructor stub
}
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;
}
}
ServletDemo3代码:
package com.kevin; import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; /**
* Servlet implementation class Demo3
*/
@WebServlet("/Demo3")
public class Demo3 extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public Demo3() {
super();
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//out.print("Demo3"); //1. display detail info by id
String id = request.getParameter("id");
Book book = (Book) Db.getAll().get(id);
if(book !=null)
{
out.write(book.getId() + "<br/>");
out.write(book.getAuthor() + "<br/>");
out.write(book.getName() + "<br/>");
out.write(book.getDescription() + "<br/>");
} //2. write cookie
String cookieValue = buildCookie(id, request);
Cookie cookie = new Cookie("bookHistory", cookieValue);
cookie.setMaxAge(30*24*3600);
cookie.setPath("/WebTest3"); response.addCookie(cookie);
} private String buildCookie(String id, HttpServletRequest request) {
//max num = 3
//bookHistory=null look:1 return:1
//bookHistory=2,3,4 look:4 return:4,2,3
//bookHistory=2,3,4 look:1 return:1,2,5
//bookHistory=2,3 look:4 return:2,3,4 String bookHistory = null;
Cookie[] cookies = request.getCookies();
for(int i=0; cookies!=null && i<cookies.length; i++)
{
if( cookies[i].getName().equals("bookHistory") )
{
System.out.println("hava bookHistory");
bookHistory = cookies[i].getValue();
}
} System.out.println("bookHistory=" + bookHistory); if(bookHistory==null)
return id; LinkedList<String> list = new LinkedList<String>(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);
}
} StringBuffer sb = new StringBuffer();
for(String id2 : list)
{
sb.append(id2 + ",");
} return sb.deleteCharAt(sb.length()-1).toString();
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }
JavaWeb -- Cookie应用实例 -- 购物历史记录的更多相关文章
- JavaWeb:Cookie处理和Session跟踪
JavaWeb:Cookie处理和Session跟踪 Cookie处理 什么是Cookie Cookie 是存储在客户端计算机上的文本文件,保留了各种跟踪信息.因为HTTP协议是无状态的,即服务器不知 ...
- JavaWeb之商品查看后历史记录代码实现
JavaWeb之商品查看后历史记录代码实现全过程解析. 历史记录思路图: 假设已经访问了商品 :1-2-3 那么历史记录就是1-2-3,如果访问了商品8,那么历史记录就是:8-1-2-3,如果再次访问 ...
- Javaweb Cookie机制
Javaweb Cookie机制 一.前言 HTTP协议是一种无状态的协议,WEB服务器本身不能识别出哪些请求是同一个浏览器发出的 ,浏览器的每一次请求都是完全孤立的,即使 HTTP1.1 支持持续连 ...
- PHP之cookie相关实例教程与经典代码
·php 中cookie和session的用法比较 ·php会话控制cookie与Session会话处理 ·php中利用cookie实现购物车实例 ·php中cookie与session应用学习笔记 ...
- Cookie简单实例
Cookie简单实例 1.创建CookieServlet package com.servlet.study; import java.io.IOException; import java.io.P ...
- JavaWeb Cookie详解
代码地址如下:http://www.demodashi.com/demo/12713.html Cookie的由来 首先我们需要介绍一下,在Web开发过程中为什么会引入Cookie.我们知道Http协 ...
- 简单利用XSS获取Cookie信息实例演示
简单利用XSS获取Cookie信息实例演示 首先要找到一个有XXS的站,这里就不整什么大站了,谷歌一下inurl:'Product.asp?BigClassName',搜出来的命中率也比较高.随便 ...
- JavaWeb——Cookie,Session学习汇总
什么是Cookie Cookie的作用 安全性能 Cookie的语法 Cookie注意细节 Cookie实例练习 什么是会话Session Session语法 Session与浏览器窗口的关系 ses ...
- 入门:JavaWeb Cookie
总结: JavaWeb 利用Cookie 存储在本地用户名和密码,设置Cookie的生存时间. 两个页面,一个登陆页面,一个登陆后的页面,在登陆页面选择是否保存Cookie(保存Cookie,下次自动 ...
随机推荐
- UVALive - 4255 - Guess (拓扑排序)
Guess 题目传送:Guess 白书例题 注意拓扑排序时,,入度同一时候为0的前缀和须要赋值为同一个数(这个数能够随机取.由于前缀和是累加的,每个a的数值都仅仅和前缀和之差有关).,由于此时能够看成 ...
- keil 中的一些设置
option for target 'target 1' 中: 第3选项output: select folder for objects :此选项是选择编译时产生的以希望文件,点击选择路径,不然这些 ...
- oracle如何进行索引监控分析和优化
在生产环境.我们会发现: ① 索引表空间 I/O 非常高 ② "db file sequential read" 等待事件也比较高 这种迹象表明.整个数据库系统.索引的 ...
- oracle浅析导致数据库性能问题的常见原因
㈠ 不合理的大表全表扫描 详见:点击打开链接 v$session_longops视图记录了超过6秒的所有SQL语句 这其中绝大部是全表扫描的语句! ㈡ 语句共享性不好 常出没在OLTP, ...
- mysql 集合函数与where条件
这里要查询的是去过的国家数(country)的次数ct大于2的人的名字 select name ,count(country) ct from sz03 where ct >2 group by ...
- 【数据挖掘】聚类之k-means(转载)
[数据挖掘]聚类之k-means 1.算法简述 分类是指分类器(classifier)根据已标注类别的训练集,通过训练可以对未知类别的样本进行分类.分类被称为监督学习(supervised learn ...
- NPTL LinuxThreads
Linux 线程模型的比较:LinuxThreads 和 NPTL 进行移植的开发人员需要了解的关键区别摘要 Vikram Shukla 2006 年 8 月 28 日发布 WeiboGoogle+用 ...
- Linq系列(7)——表达式树之ExpressionVisitor
大家好,由于今天项目升级,大家都在获最新代码,所以我又有时间在这里写点东西,跟大家分享. 在上一篇的文章中我介绍了一个dll,使大家在debug的时候可以可视化的看到ExpressionTree的Bo ...
- php扩展安装phpize
安装php(fastcgi模式)的时候,常常有这样一句命令:/usr/local/webserver/php/bin/phpize 一.phpize是干嘛的? phpize是什么东西呢?php官方的说 ...
- Obj-C数组以及字符串拼接与分割
本文转载至 http://mobile.51cto.com/iphone-392148.htm Obj-C只是增加了一点“特殊语料”的C语言,所以可以用printf()代替NSLog().但我们建议使 ...