1.

页面一:主页面                                         页面二: 详细显示页面

JavaWeb -- Cookie应用实例 -- 购物历史记录-LMLPHP 
JavaWeb -- Cookie应用实例 -- 购物历史记录-LMLPHP

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
} }
05-11 20:25