Cookie案例分析

一、案例- 显示用户上次访问的时间

  当用户第一次访问该页面的时候提示:你好,你是第一次访问本页面,当前时间为:2016-11-3 22:10:30

  第n次访问该页面时:欢迎回来,你上次访问的时间是:2016-11-3 22:10:30,当前时间是:2016-11-3 22:10:30

 

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.gqx.cookie;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class Test extends HttpServlet {
 
    private static final long serialVersionUID = 1L;
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");    
        //获取当前时间
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time =format.format(new Date());
        Cookie cookie =new Cookie("lastTime", time);
        cookie.setPath("/CookieSession");
        cookie.setMaxAge(1*30*24*60*60);
        response.addCookie(cookie);
         
         
        Cookie[] cookies=request.getCookies();
        if (cookies!=null) {
            response.getWriter().write("<html><body><p>欢迎回来,你上次访问的时间是:"+cookies[0].getValue()+"      "+"当前时间是:"+time+"</p></body></html>");
            cookie.setValue(time);
            cookie.setMaxAge(1*30*24*60*60);
            response.addCookie(cookie);
        }else {
            response.getWriter().write("<html><body><p>你是首次访问本网站,当前时间是:"+time+"</p></body></html>");
        }
    }
 
}

  


二:案例-查看用户浏览器过的商品

要实现浏览记录,同时将最近浏览的商品浏览最近时间排好顺序,同时只要求显示三条记录

思路:由于要求不易实现,逻辑不易理清,我们先建一个web项目,然后建立好分包目录

首先我们建立实体对象,即产品对象,对其进行封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.gqx.entity;
 
public class Product {
    private String id;
    private String name;
    private float price;
    private String proType;
    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 Float getPrice() {
        return price;
    }
    public void setPrice(Float price) {
        this.price = price;
    }
    public String getProType() {
        return proType;
    }
    public void setProType(String proType) {
        this.proType = proType;
    }
     
 
    public Product() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Product(String id, String name, float price, String proType) {
        super();
        this.id = id;
        this.name = name;
        this.price = price;
        this.proType = proType;
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", name=" + name + ", price=" + price
                + ", proType=" + proType + "]";
    }
     
 
}

然后定义好一个数据访问对象的操作方法的类,里面有我们需要对对象操作的全部方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.gqx.productDao;
 
import java.util.ArrayList;
import java.util.List;
 
import com.gqx.entity.Product;
 
/**
 *该类存放对product的相关操作,如查询、(CRDU)
 * @author Administrator
 *
 */
public class ProductDao {
    //模拟数据库存放所有商品
    private static List<Product> products=new ArrayList<Product>();
    //初始化所有产品,用静态代码块完成,只执行一次
    static{
        for (int i = 1; i < 11; i++) {
                products.add(new Product("00"+i, "笔记本"+i, 4500+i*100, "厂商"+i));
        }
    }
     
    //提供查询所有商品的方法
    public List<Product> findAll(){
        return this.products;
    }
     
    //根据id去查询某产品
    public Product getProduct(String id){
        for (Product product:products) {
            if (product.getId().equals(id)) {
                return product;
            }
        }
        return null;
    }
 
}

最后就是我们要访问的servlet了,本案例的重点也在此处

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.gqxservlet;
 
import java.io.IOException;
import java.io.PrintWriter;
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 com.gqx.entity.Product;
import com.gqx.productDao.ProductDao;
 
public class ListServlet extends HttpServlet {
 
    /**
     * 首页:查询所有商品的servlet
     */
    private static final long serialVersionUID = 1L;
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         
        response.setContentType("text/html;charset=utf-8");
        //查询“数据库”,读出所有的商品。
        ProductDao dao=new ProductDao();        //对操作对象的实例化
        List<Product> products=dao.findAll();
         
        PrintWriter out = response.getWriter();
         
        //把所有的产品显示到浏览器中
        String html="";
        html+="<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"><HTML><HEAD><TITLE>所有商品列表</TITLE></HEAD><BODY>";
        html+="<table width='600px' border='1' align='center'>";
        html+="<tr><th>编号</th><th>商品名称</th><th>商品类型</th></tr>";
        //遍历所有的商品
        for(Product product:products){
            String path=request.getContextPath()+"/DetailServlet?id="+product.getId();
            html+="<tr><td>"+product.getId()+"</td><td>"+product.getName()+"</td><td><a href='"+path+"'>详细信息</a></td></tr>";
        }
        html+="  </table>";
         
         
        //处理上一次访问的cookie,得到上一次啊访问的数据
        String str="</br>";
        Cookie[] cookies=request.getCookies();
        if (cookies!=null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("proHist")) {
                    str+="你上次浏览的商品是:</br>";
                    String proHist=cookie.getValue();
                    String[] ids=proHist.split(",");
                    for (String string : ids) {
                        //查询“数据库”,查询对于的商品
                        Product p=dao.getProduct(string);
                        //显示在浏览器上
                        str+=p.getId()+"  "+p.getName()+"  "+p.getPrice()+"</br>";
                    }
                }
            }
        }else {
            str+="<p>你是第一次访问本网站</p>";
        }
         
        html=html+str;
        html+="</BODY></HTML>";
        out.write(html);
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
 
}

 然后我们来定义内容页,该页记录着cookie,同时对cookie进行更改,然后将其发送给服务器。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.gqxservlet;
 
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
 
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 com.gqx.entity.Product;
import com.gqx.productDao.ProductDao;
 
public class DetailServlet extends HttpServlet {
 
    /**
     * 商品详细信息页面
     */
    private static final long serialVersionUID = 1L;
 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
 
        response.setContentType("text/html;charset=utf-8");
        ProductDao products=new ProductDao();
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>商品详细信息</TITLE></HEAD>");
        out.println("  <BODY>");
        String id=request.getParameter("id");
        Product product=products.getProduct(id);
        //打印出具体的商品信息
        String html="";
        html+="<table width='300px' border='1' align='center'>";
        html+="<tr><th>"+product.getId()+"产品的信息</th></tr>";
        html+="<tr><td>商品编号:</td><td>"+product.getId()+"</td><tr><td>商品名称:</td><td>"+product.getName()+"</td></tr><tr><td>商品类型</td><td>"+product.getProType()+"</td></tr><tr><td>商品价格:</td><td>"+product.getPrice()+"</td></tr>";
        html+="<center><a href='"+request.getContextPath()+"/ListServlet'>返回上一级</a></center>";
        out.print(html);
        out.println("  </table>");
         
        //设置cookie值
        Cookie cookie =new Cookie("proHist", createValue(request,id));
        cookie.setMaxAge(30*24*60*60);
        response.addCookie(cookie);
        out.println("</BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }
     
 
    /**
     * 显示以前访问的商品,如何保存其cookie值
     * @param request
     * @return
     *    当前cookie                  传入 id               最终的cookie
     *          无                               1                           1
     *          1                                   2                           2,1
     *          2,1                             1                           1,2
     *          1,2                             3                           3,1,2
     */
 
    private String createValue(HttpServletRequest request,String id) {
        // TODO Auto-generated method stub
        Cookie[] cookies=request.getCookies();
        String proHist=null;
         
        if (cookies!=null) {
        //如果浏览器端有cookie,则从其中取回cookie值
            for (Cookie cookie : cookies) {
                //查找名为proHist的cookie
                if (cookie.getName().equals("proHist")) {
                    proHist=cookie.getValue();
                }  
            }
        }
         
        //如果cookie为空或者proHist为空,则返回当前id
        if (cookies==null || proHist==null) {
            return id;
        }
         
        /**
         * 剩下的则是对字符串中的cookie值(形如[1,2,3])进行操作,但对仅仅对字符串操作太过于麻烦
         * 这个时候我们可以换一种思维,将其转化为集合的形式 在jdk中有一个方法直接将字符串数组转化为list的形式  
         *  static <T> List<T> asList(T... a)  返回一个受指定数组支持的固定大小的列表。
         *  同时Collection又是List的子接口
         */
        String string[]=proHist.split(",");
        Collection<String> collection = Arrays.asList(string);
         
        /**
         * 这个时候我们又发现了一个问题,即便是集合,但是对集合的频繁操作太过于麻烦,而且集合缺少一些方便删除添加的操作
         * 我们知道对列表的频繁操作,最方便的是linkedlist链接,我们又发现在jdk中有如下的方法,可以方便我们查找
         * LinkedList(Collection<? extends E> c) 构造一个包含指定 collection 中的元素的列表,这些元素按其 collection 的迭代器返回的顺序排列
         */
         
        LinkedList list=new LinkedList(collection);
         
         
        if (list.size()<3) {
            //首先判断该cookie值是否超过三个
            if (list.contains(id)) {
                //当cookie值中重复 (id=1    cookie=2,1)
                list.remove(id);
                list.addFirst(id);
            }else {
                list.addFirst(id);
            }
        }else {
            //其次判断该cookie值若超过三个
            if (list.contains(id)) {
                //当cookie值中重复 (id=1    cookie=2,1,3)
                list.remove(id);
                list.addFirst(id);
            }else {
                //不重复,去掉最后一个,将id加到第一个去
                list.removeLast();
                list.addFirst(id);
            }
        }
         
        //将集合转化为字符串
        String valueString="";
        for (Object object : list) {
            valueString+=object+",";
        }
         
        //去掉多余的逗号
        valueString=valueString.substring(0, valueString.length()-1);
        return valueString;
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
 
}

  以上将字符做的操作十分的值得借鉴,其中linkedList是一个功能很强大的链表对象,而Collection又是一个不错的方法去将字符串数组转化为集合。

1
2
        String string[]=proHist.split(",");
Collection<String> collection = Arrays.asList(string);                   

  

 

posted @   晓乎  阅读(766)  评论(0)    收藏  举报
编辑推荐:
· 从 Redis 客户端超时到 .NET 线程池挑战
· C23和C++26的#embed嵌入资源指南
· 「EF Core」框架是如何识别实体类的属性和主键的
· 独立开发,这条路可行吗?
· 我在厂里搞 wine 的日子
阅读排行:
· 他没买 iPad,而是花了半年时间,为所有“穷学生”写了个笔记神器
· Visual Studio 现已支持新的、更简洁的解决方案文件(slnx)格式
· 只需一行命令,Win11秒变Linux开发主机!
· 从 Redis 客户端超时到 .NET 线程池挑战:饥饿、窃取与阻塞的全景解析
· 2025年中总结:我想我克服公众演讲的恐惧了,一个社恐分子突破自我的故事
总访问: counter for blog 次
点击右上角即可分享
微信分享提示