Cookie的案例:记录用户最近商品的访问记录
--------------------------------------------------------------------------------------------
public class Book {
private String id;
private String name;
private String author;
private float price;
private String description;
public Book(){}
public Book(String id, String name, String author, float price,String description) {
super();
this.id = id;
this.name = name;
this.author = author;
this.price = price;
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 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 [author=" + author + ", description=" + description
+ ", id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
--------------------------------------------------------------------------------------------
public class BookDB {
// key: 书的id value: id对应的书对象
private static Map<String, Book> books = new LinkedHashMap<String, Book>();
static{
books.put("1", new Book("1", "葵花宝典", "葛付以", 5.00f, "欲练此功"));
books.put("2", new Book("2", "玉女心经", "朱巧玲", 8.00f, "欲练此功"));
books.put("3", new Book("3", "辟邪剑法", "邹海洋", 5.00f, "欲练此功"));
books.put("4", new Book("4", "金瓶梅", "刘建平", 15.00f, "古代爱情小说"));
books.put("5", new Book("5", "红楼梦", "曹雪芹", 105.00f, "古代诺贝"));
}
public static Book findBookById(String bookId){
return books.get(bookId); // map集合的方法
}
public static Map<String,Book> findAllBooks(){
return books;
}
}
--------------------------------------------------------------------------------------------
// 常量接口设计模式
public interface Constants {
String BOOK_HISTORY = "bookHistory"; // 默认为静态和公共的
}
--------------------------------------------------------------------------------------------
// 显示所有的书, 并显示用户最近的浏览记录 Cookie: bookHistory=1-2-3
public class ShowBookServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;chatset=UTF-8");
PrintWriter out = response.getWriter();
// 显示所有书籍
out.write("<h1>本站有以下好书</h1>");
Map<String,Book> books = BookDB.findAllBooks();
for(Map.Entry<String,Book> me : books.entrySet()){
out.write(me.getValue().getName() + " <a href='
/day08/servlet/ShowBookDetailServlet?id=" + me.getKey() + "'
>查看详情</a><br/>");
}
// 显示用户最近的浏览记录: cookie: bookHistory=1-2-3
out.write("<hr/>");
out.write("<h3>您最近的商品浏览记录:</h3>");
Cookie[] cs = request.getCookies();
for(int i=0; cs!=null&&i<cs.length; i++){
if(Constants.BOOK_HISTORY.equals(cs[i].getName())){
String value = cs[i].getValue(); // 1-3-2.
// 显示书名
String ids[] = value.split("\\-");
for(String id : ids){
out.write(BookDB.findBookById(id).getName() + "<br/>");
}
break;
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
--------------------------------------------------------------------------------------------
// 显示书籍的详细内容 并向客户端写bookHistory的Cookie
// 学习 LRU算法的书写
public class ShowBookDetailServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;chatset=UTF-8");
PrintWriter out = response.getWriter();
// 显示书籍的详细内容
String id = request.getParameter("id");
Book book = BookDB.findBookById(id);
out.write(book.toString());
// 向客户端写bookHistory的cookie bookHistory=1-3-2
String ids = makeIds(request,id);
Cookie c = new Cookie(Constants.BOOK_HISTORY,ids);
c.setMaxAge(Integer.MAX_VALUE);
c.setPath(request.getContextPath());
response.addCookie(c);
}
// id字符串 : 使用LRU算法
// 原有的cookie中的id 当前新访问的书的id 应该写回的id bookHistory的取值
// a. cookie[] cs为null 1 1
// b. 没有bookHistory中的cookie 1 1
// c. 1 2 2-1
// d. 2-1 1 1-2
// e. 1-2 3 3-1-2
// f. 1-2-3 2 2-1-3
// g. 2-1-3 4 4-2-1
public String makeIds(HttpServletRequest request, String id) {
// a
Cookie cs[] = request.getCookies();
if(cs==null)
return id;
// b(cs不为空)
Cookie cookie = null;
for(Cookie c : cs){
if(Constants.BOOK_HISTORY.equals(c.getName())){
cookie = c;
break;
}
}
if(cookie == null)
return id;
// cdefg
String ids[] = cookie.getValue().split("\\-");
LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids)); // [1,2,3]
// cde
if(list.size() < 3){
if(list.contains(id)){
list.remove(id);
}
list.addFirst(id);
}else{
// fg
if(list.contains(id)){
list.remove(id);
}else{
list.removeLast();
}
list.addFirst(id);
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<list.size(); i++){
if(i>0)
sb.append("-");
sb.append(list.get(i));
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
--------------------------------------------------------------------------------------------
public class Book {
private String id;
private String name;
private String author;
private float price;
private String description;
public Book(){}
public Book(String id, String name, String author, float price,String description) {
super();
this.id = id;
this.name = name;
this.author = author;
this.price = price;
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 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 [author=" + author + ", description=" + description
+ ", id=" + id + ", name=" + name + ", price=" + price + "]";
}
}
--------------------------------------------------------------------------------------------
public class BookDB {
// key: 书的id value: id对应的书对象
private static Map<String, Book> books = new LinkedHashMap<String, Book>();
static{
books.put("1", new Book("1", "葵花宝典", "葛付以", 5.00f, "欲练此功"));
books.put("2", new Book("2", "玉女心经", "朱巧玲", 8.00f, "欲练此功"));
books.put("3", new Book("3", "辟邪剑法", "邹海洋", 5.00f, "欲练此功"));
books.put("4", new Book("4", "金瓶梅", "刘建平", 15.00f, "古代爱情小说"));
books.put("5", new Book("5", "红楼梦", "曹雪芹", 105.00f, "古代诺贝"));
}
public static Book findBookById(String bookId){
return books.get(bookId); // map集合的方法
}
public static Map<String,Book> findAllBooks(){
return books;
}
}
--------------------------------------------------------------------------------------------
// 常量接口设计模式
public interface Constants {
String BOOK_HISTORY = "bookHistory"; // 默认为静态和公共的
}
--------------------------------------------------------------------------------------------
// 显示所有的书, 并显示用户最近的浏览记录 Cookie: bookHistory=1-2-3
public class ShowBookServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;chatset=UTF-8");
PrintWriter out = response.getWriter();
// 显示所有书籍
out.write("<h1>本站有以下好书</h1>");
Map<String,Book> books = BookDB.findAllBooks();
for(Map.Entry<String,Book> me : books.entrySet()){
out.write(me.getValue().getName() + " <a href='
/day08/servlet/ShowBookDetailServlet?id=" + me.getKey() + "'
>查看详情</a><br/>");
}
// 显示用户最近的浏览记录: cookie: bookHistory=1-2-3
out.write("<hr/>");
out.write("<h3>您最近的商品浏览记录:</h3>");
Cookie[] cs = request.getCookies();
for(int i=0; cs!=null&&i<cs.length; i++){
if(Constants.BOOK_HISTORY.equals(cs[i].getName())){
String value = cs[i].getValue(); // 1-3-2.
// 显示书名
String ids[] = value.split("\\-");
for(String id : ids){
out.write(BookDB.findBookById(id).getName() + "<br/>");
}
break;
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
--------------------------------------------------------------------------------------------
// 显示书籍的详细内容 并向客户端写bookHistory的Cookie
// 学习 LRU算法的书写
public class ShowBookDetailServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;chatset=UTF-8");
PrintWriter out = response.getWriter();
// 显示书籍的详细内容
String id = request.getParameter("id");
Book book = BookDB.findBookById(id);
out.write(book.toString());
// 向客户端写bookHistory的cookie bookHistory=1-3-2
String ids = makeIds(request,id);
Cookie c = new Cookie(Constants.BOOK_HISTORY,ids);
c.setMaxAge(Integer.MAX_VALUE);
c.setPath(request.getContextPath());
response.addCookie(c);
}
// id字符串 : 使用LRU算法
// 原有的cookie中的id 当前新访问的书的id 应该写回的id bookHistory的取值
// a. cookie[] cs为null 1 1
// b. 没有bookHistory中的cookie 1 1
// c. 1 2 2-1
// d. 2-1 1 1-2
// e. 1-2 3 3-1-2
// f. 1-2-3 2 2-1-3
// g. 2-1-3 4 4-2-1
public String makeIds(HttpServletRequest request, String id) {
// a
Cookie cs[] = request.getCookies();
if(cs==null)
return id;
// b(cs不为空)
Cookie cookie = null;
for(Cookie c : cs){
if(Constants.BOOK_HISTORY.equals(c.getName())){
cookie = c;
break;
}
}
if(cookie == null)
return id;
// cdefg
String ids[] = cookie.getValue().split("\\-");
LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids)); // [1,2,3]
// cde
if(list.size() < 3){
if(list.contains(id)){
list.remove(id);
}
list.addFirst(id);
}else{
// fg
if(list.contains(id)){
list.remove(id);
}else{
list.removeLast();
}
list.addFirst(id);
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<list.size(); i++){
if(i>0)
sb.append("-");
sb.append(list.get(i));
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
--------------------------------------------------------------------------------------------