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应用实例 -- 购物历史记录的更多相关文章

  1. JavaWeb:Cookie处理和Session跟踪

    JavaWeb:Cookie处理和Session跟踪 Cookie处理 什么是Cookie Cookie 是存储在客户端计算机上的文本文件,保留了各种跟踪信息.因为HTTP协议是无状态的,即服务器不知 ...

  2. JavaWeb之商品查看后历史记录代码实现

    JavaWeb之商品查看后历史记录代码实现全过程解析. 历史记录思路图: 假设已经访问了商品 :1-2-3 那么历史记录就是1-2-3,如果访问了商品8,那么历史记录就是:8-1-2-3,如果再次访问 ...

  3. Javaweb Cookie机制

    Javaweb Cookie机制 一.前言 HTTP协议是一种无状态的协议,WEB服务器本身不能识别出哪些请求是同一个浏览器发出的 ,浏览器的每一次请求都是完全孤立的,即使 HTTP1.1 支持持续连 ...

  4. PHP之cookie相关实例教程与经典代码

    ·php 中cookie和session的用法比较 ·php会话控制cookie与Session会话处理 ·php中利用cookie实现购物车实例 ·php中cookie与session应用学习笔记 ...

  5. Cookie简单实例

    Cookie简单实例 1.创建CookieServlet package com.servlet.study; import java.io.IOException; import java.io.P ...

  6. JavaWeb Cookie详解

    代码地址如下:http://www.demodashi.com/demo/12713.html Cookie的由来 首先我们需要介绍一下,在Web开发过程中为什么会引入Cookie.我们知道Http协 ...

  7. 简单利用XSS获取Cookie信息实例演示

    简单利用XSS获取Cookie信息实例演示   首先要找到一个有XXS的站,这里就不整什么大站了,谷歌一下inurl:'Product.asp?BigClassName',搜出来的命中率也比较高.随便 ...

  8. JavaWeb——Cookie,Session学习汇总

    什么是Cookie Cookie的作用 安全性能 Cookie的语法 Cookie注意细节 Cookie实例练习 什么是会话Session Session语法 Session与浏览器窗口的关系 ses ...

  9. 入门:JavaWeb Cookie

    总结: JavaWeb 利用Cookie 存储在本地用户名和密码,设置Cookie的生存时间. 两个页面,一个登陆页面,一个登陆后的页面,在登陆页面选择是否保存Cookie(保存Cookie,下次自动 ...

随机推荐

  1. IOS开发——Core Graphics &amp; Core Animation

    好久没写过blog了.首先了解下近期苹果和IOS方面的最新消息. 1.WWDC2014在上个月举行了,与2013年一样.今年WWDC没公布硬件产品和新品(假设你懂cook你就会期待今年秋季公布会.估计 ...

  2. Unity3d 实现鼠标左键点击地形使角色移动到指定地点[脚本]

    Unity3d 实现鼠标左键点击地形使角色移动到指定地点[脚本] 2013-02-19 15:29:33     我来说两句      作者:nnsword 收藏    我要投稿 其中涉及,移动速度, ...

  3. 通过pyenv进行多版本python管理

    1.安装pyenv brew install pyenv 2.配置.zshrc文件 export PYENV_ROOT=/usr/local/var/pyenv if which pyenv > ...

  4. publish over ssh 实现 Jenkins 远程部署

    Jenkins远程部署,一开始没有任何头绪,想了很多方案. 因为两台机器都是windows系统,所以想到publish over cifs, 但是这个网上资料太少,貌似只能内网使用.又想到了Jenki ...

  5. python学习 01 变量

    1.变量不是‘盒子’. 1.1 不同的值,变量名没变,   变量地址也会变. 1.2 相同的值,不同的变量名,变量地址是相同的

  6. 在Hierarchy面板隐藏物体

    PlantObjPreview.hideFlags = HideFlags.HideInHierarchy;

  7. MUI 清除缓存

    mui 清除但是在ios和安卓稍微有点区别, ios可以清除的很彻底,下载文件也能删除: 安卓能清理缓存,但是不能删除下载的文件: plus.cache.calculate(function(size ...

  8. Linux删除乱码文件的方法

    当文件名为乱码的时候,无法通过键盘输入文件名,所以在终端下就不能直接利用rm,mv等命令管理文件了. 我们可以通过以下几种方法删除linux下的乱码文件.(文件名为乱码) l  方法1 我们知道每个文 ...

  9. Configure the modules to be find by modprobe

    sudo ln -s /path/to/module.ko /lib/modules/`uname -r` sudo depmod -a #depmod will output a dependenc ...

  10. 【原创】Hibernate自动生成(1)

    本实战是博主初次学习Java,分析WCP源码时,学习HibernateTools部分的实战,由于初次接触,难免错误,仅供参考,希望批评指正. 开发环境: Eclipse Version: Photon ...