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. Django--登录认证

    COOKIE 与 SESSION 概念 cookie的使用,不止局限于我们所使用的登录认证,cookie不属于http协议范围,由于http协议无法保持状态,但实际情况,我们却又需要“保持状态”,因此 ...

  2. 2013 年最好的 20 款免费 jQuery 插件

    2013 年最好的 20 款免费 jQuery 插件 oschina 发布于: 2014年01月11日 (8评) 分享到  新浪微博腾讯微博 收藏+99 互联网上面有很多 jQuery 插件,这里我们 ...

  3. php实现等比例不失真缩放上传图片的方法

    本文实例分析了php实现等比例不失真缩放上传图片的方法.分享给大家供大家参考,具体如下: 有时上传图片时因为图片太大了,不仅占用空间,消耗流量,而且影响浏(图片的尺寸大小不一).下面分享一种等比例不失 ...

  4. spring-test-dbunit的配置和使用

    1.数据源配置 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" ...

  5. Y2K Accounting Bug - 2586

      Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 11271   Accepted: 5672 Description Ac ...

  6. ios NavigationViewController跳转以及返回传值

    (一)使用NavigationViewController进行页面跳转时,应该使用pushViewController方法来跳转至下一页面.这种话.下一页面相同在NavigationViewContr ...

  7. ASP.NET动态网站制作(22)-- ADO.NET(1)

    前言:这节课开始真正地学习WEB开发,ADO.NET就是一组允许.NET开发人员使用标准的.机构化的,甚至无连接的方式与数据交互的技术.所属的类库为:System.Data.dll. 内容: 1.AD ...

  8. <转载> 为什么在Python里推荐使用多进程而不是多线程?

    经常我们会听到老手说:“Python下多线程是鸡肋,推荐使用多进程!”,但是为什么这么说呢?                要知其然,更要知其所以然.所以有了下面的深入研究: 首先强调背景:     ...

  9. SpringMVC结合REST

    一.什么是REST REST即 Representational State Transfer,也就是(资源)表现层状态转化.资源是指网络上的一个实体或者说是网络上的一个具体信息. 每种资源对应一个特 ...

  10. MySQL存储过程-通过数据库里已存在的IP查询城市

    CREATE DEFINER=`mazey`@`%` PROCEDURE `sp_find_city_by_ip`(IN `in_visitor_ip` varchar(20),OUT `out_vi ...