java利用 cookie 进行展示你所浏览过的的商品

最近好烦~ 不过没什么大不了的

一个商品的展示界面,可以看到你以前浏览过的的界面。利用cookie
/**
 *  商品的列表界面
 */
public class Servlet_products extends HttpServlet {
       
     public  static final String bookHistory="bookHistory";
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //1、展示商品的列表
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write("商品的信息如下"+"<br/>");
        HashMap<String, Book> map=(HashMap<String, Book>) DB.getAll();
         Set<Entry<String, Book>> set = map.entrySet();
         for (Entry<String, Book> entry : set) {
            Book book=entry.getValue();
            //展示商品的数据
            out.write("<a href='/Demo2/Servlet_productInfo?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a>");
            out.write("<br/>");
        }
         
         //2.展示以前浏览过的数据
        out.write("<br/><br/>您曾经浏览过的商品:<br/>" );
        Cookie[] cookies = request.getCookies();
        for (int i = 0;cookies!=null&& i < cookies.length; i++) {
            Cookie c=cookies[i];
            if(c.getName().equals(bookHistory))
            {
                //是这个界面给浏览器的
                String value=c.getValue();
                //我们存入用户浏览过商品的id    是 1_2_3 这种格式进行存储的
                String ids[] = value.split("\\_");   
                for(String id: ids){
                    Book book = (Book) DB.getAll().get(id);
                    out.write(book.getName() + "<br/>");
                }
            }
        }
         
    }

     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         
        doGet(request, response);
    }
    
    //模拟数据库
    public static class DB {
        
        //有序的 map
        public static LinkedHashMap<String,Book> map=new LinkedHashMap<String,Book>();
        static {
            //静态代码块 用于初始化 map的信息
                map.put("1", new Book("1","javaweb开发","老张","一本好书"));
                map.put("2", new Book("2","spring开发","老黎","一本好书"));
                map.put("3", new Book("3","hibernate开发","老佟","一本好书"));
                map.put("4", new Book("4","struts开发","老毕","一本好书"));
                map.put("5", new Book("5","ajax开发","老张","一本好书"));
        }
        
        public static Map<String,Book> getAll(){
            return map;
        }
    }
    
    
    //商品的信息
    public static 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;
         
        
    }
    }

    
}

商品的详情界面

package jemo.cookie.demo;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import jemo.cookie.demo.Servlet_products.Book;
import jemo.cookie.demo.Servlet_products.DB;

/**
 *  点击具体的商品挑转到界面
 */
public class Servlet_productInfo extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         
 
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        //1.根据用户带过来的id号,显示商品的详细信息
        String id = request.getParameter("id");
        Book book = (Book) DB.getAll().get(id);
        
        out.write("您要查看的书的详细信息如下:<br/><br/>");
        out.write(book.getId() + "<br/>");  
        out.write(book.getName() + "<br/>");
        out.write(book.getAuthor() + "<br/>");
        out.write(book.getDescription() + "<br/>");
        
        
        //2.给用户回送包含当前商品id的cookie
        String bookHistory = makeHistory(request,id);    //  3_2
        Cookie cookie = new Cookie(Servlet_products.bookHistory,bookHistory);
        cookie.setMaxAge(1*30*24*3600);
        
        response.addCookie(cookie); 
        
    }
      
    /**
     * 得到要给浏览器cookie
     * @param request
     * @param id
     * @return
     */
    private String makeHistory(HttpServletRequest request, String id) {
        
        String bookHistory = null;
        Cookie cookies[] = request.getCookies();
        for(int i=0;cookies!=null&&i<cookies.length;i++){
            if(cookies[i].getName().equals(Servlet_products.bookHistory)){
                bookHistory = cookies[i].getValue();
            }
        }
        
        //  bookHistory=null      1    bookHistory=1
        //  bookHistory=3_1_5     1    bookHistory=1_3_5
        //  bookHistory=3_2_5     1    bookHistory=1_3_2
        //  bookHistory=3_2       1    bookHistory=1_3_2
        
        
        //  bookHistory=null      1    bookHistory=1
        if(bookHistory==null){
            return id;
        }
        
        List l = Arrays.asList(bookHistory.split("\\_"));   //[3,4]  //数组  链接
        LinkedList<String> list = new  LinkedList();//对数据增删更有效
        list.addAll(l);
        
        if(list.contains(id)){
            //  bookHistory=3_1_5     1    bookHistory=1_3_5
            list.remove(id);
            list.addFirst(id);
        }else{
            if(list.size()>=3){
                //  bookHistory=3_2_5     1    bookHistory=1_3_2
                list.removeLast();
                list.addFirst(id);
            }else{
                //  bookHistory=3_2       1    bookHistory=1_3_2
                list.addFirst(id);
            }
        }
        
        StringBuffer sb = new StringBuffer();  //2_3_4
        for(String lid: list){
            sb.append(lid + "_");
        }
        
        return sb.deleteCharAt(sb.length()-1).toString();//删除最后的_
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,679评论 25 708
  • 一、基础知识篇:Http Header之User-AgentUser Agent中文名为用户代理,是Http协议中...
    iPhone阅读 15,891评论 0 13
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 不知是不是只有四川才有'’吃独食''这一说,按其传统释义意思是不爱分享。而我这里要说的是‘‘独食者’’。想分而不得...
    谭niuniu阅读 652评论 1 11