Cookie应用之用户上次访问时间、用户浏览记录(转)

本文介绍了一种利用Servlet和Cookie技术实现用户访问时间和浏览历史记录的方法。通过编写HistServlet来记录用户的访问时间并显示给用户,同时使用ListServlet和DetailServlet记录用户的商品浏览历史,实现了最近浏览商品的展示。

原文链接:http://blog.youkuaiyun.com/qq_34944851/article/details/53282879


一、用户上次访问时间: 
1、需求及分析图: 

2、功能实现: 
1)代码部分:

package sram.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 HistServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取当前时间
        SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String currentTime = date.format(new Date());

        //取得cookie
        Cookie[] cookies = request.getCookies();
        String lastTime = null;
        if(cookies!=null){
            for(Cookie c:cookies){
                //有lastTime的cookie,已经是第n次访问
                if(c.getName().equals("lastTime")){
                    lastTime = c.getValue();//获取上次访问的时间
                    //第n次访问
                    //把上次显示时间显示到浏览器
                    response.getWriter().write("您上次访问的时间为:"+lastTime+"当前时间为:"+currentTime);
                    //更新cookie
                    c.setValue(currentTime);
                    //设置一个月的cookie有效期
                    c.setMaxAge(60*60*24*30);
                    //把更新后的cookie发送到浏览器
                    response.addCookie(c);
                    break;
                }
            }
        }

        //第一次访问(没有cookie 或 有cookie,但没有名为lastTime的cookie)
        if(cookies==null||lastTime==null){
            //显示当前时间到浏览器
            response.getWriter().write("欢迎您的首次访问,本次访问的时间为:"+currentTime);
            //创建Cookie对象
            Cookie cookie = new Cookie("lastTime",currentTime);
            cookie.setMaxAge(60*60*24*30);
            //把cookie发送到浏览器保存
            response.addCookie(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

2)效果: 

二、用户浏览记录: 
1、需求及分析: 

2、工程架构及保存Cookie的值的分析: 

3、功能实现: 
1)代码:

package sram.entity;
public class Product {
    private String id;
    private String proName;
    private String proType;
    private double price;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getProName() {
        return proName;
    }
    public void setProName(String proName) {
        this.proName = proName;
    }
    public String getProType() {
        return proType;
    }
    public void setProType(String proType) {
        this.proType = proType;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public Product(String id, String proName, String proType, double price) {
        super();
        this.id = id;
        this.proName = proName;
        this.proType = proType;
        this.price = price;
    }
    public Product() {
        super();
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", proName=" + proName + ", proType="
                + proType + ", price=" + price + "]";
    }
}
    
  • 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
package sram.dao;
import java.util.ArrayList;
import java.util.List;
import sram.entity.Product;
/**
 * 该类中存放对Prodcut对象的CRUD方法
 */
public class ProductDao {
    //模拟数据库,存放所有商品数据
    private static List<Product> data = new ArrayList<Product>();
    /**
     * 初始化商品数据
     */
    //静态代码块,只执行一次
    static{
        for(int i=0;i<=10;i++){
            data.add(new Product(""+i,"苹果"+i,"iphone"+i,3700.0+i*100));
        }
    }
    /**
     * 提供查询所有商品的方法
     */
    public List<Product> findAll(){
        return data;
    }
    /**
     * 提供根据编号查询商品的方法
     */
    public Product findById(String id){
        for(Product p:data){
            if(p.getId().equals(id)){
                return p;
            }   
        }
        return null;
    }
}
    
  • 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
package sram.servlet;
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 sram.dao.ProductDao;
import sram.entity.Product;
public class ListServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //1.读取数据库,查询商品列表
        ProductDao dao = new ProductDao();
        List<Product> list = dao.findAll();
        //2.把商品显示到浏览器   
        PrintWriter writer = response.getWriter();
        String html = "";
        html += "<html>";
        html += "<head>";
        html += "<title>显示商品列表</title>";
        html += "</head>";
        html += "<body>";
        html += "<table border='1' align='center' width='600px'>";
        html += "<tr>";
        html += "<th>编号</th><th>商品名称</th><th>商品型号</th><th>商品价格</th>";
        html += "</tr>";
        if(list!=null){
            for(Product p:list){
                html += "<tr>";
                // request.getContentType()+"/DetailServlet?id="+p.getId() 等价于"/historypro/DetailServlet?id=值"
                //访问DetailServlet的servlet程序,同时传递id的值为参数
                html += "<td>"+p.getId()+"</td><td><a href="+request.getContextPath()+"/DetailServlet?id="+p.getId()+">"+p.getProName()+"</a></td><td>"+p.getProType()+"</td><td>"+p.getPrice()+"</td>";
                html += "<tr>";
            }
        }
        html += "</table>";
        /**
         * 显示浏览过的商品
         */
        html += "最近浏览过的商品:<br/>";
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for(Cookie c:cookies){
                if(c.getName().equals("historypro")){
                    String historypro = c.getValue();
                    String[] ids = historypro.split(",");
                    //遍历浏览过的商品id
                    for(String id:ids){
                        //查询数据库,查询对应的商品
                        Product product = dao.findById(id);
                        //显示到浏览器
                        html += ""+product.getId()+"&nbsp;"+product.getProName()+"&nbsp;"+product.getPrice()+"<br/>";
                    }
                }
            }
        }
        html += "</body>";
        html += "</html>";
        writer.write(html);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}
    
  • 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
package sram.servlet;
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 sram.dao.ProductDao;
import sram.entity.Product;
public class DetailServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        ProductDao dao = new ProductDao();
        //1.获取编号
        String id = request.getParameter("id");
        //2.到数据库中查询对应编号的商品
        Product product = dao.findById(id);
        //3.显示到浏览器
        PrintWriter writer = response.getWriter();
        String html = "";
        html += "<html>";
        html += "<head>";
        html += "<title>显示商品详细</title>";
        html += "</head>";
        html += "<body>";
        html += "<table border='1' align='center' width='300px'>";
        if(product!=null){
            html += "<tr><th>编号:</th><td>"+product.getId()+"</td></tr>";
            html += "<tr><th>商品名称:</th><td>"+product.getProName()+"</td></tr>";
            html += "<tr><th>商品型号:</th><td>"+product.getProType()+"</td></tr>";
            html += "<tr><th>商品价格:</th><td>"+product.getPrice()+"</td></tr>";
        }
        html += "</table>";
        html += "<center><a href='"+request.getContextPath()+"/ListServlet'>[返回列表]</a></center>";
        html += "</body>";
        html += "</html>";
        writer.write(html);
        /**
         * 创建cookie,并发送
         */
        //1.创建cookie
        Cookie cookie = new Cookie("historypro",createValue(request,id));
        cookie.setMaxAge(60*60*24*30);
        //2.发送cookie
        response.addCookie(cookie);
    }

    /**
     * 生成cookie的值
     * 分析:
     *          当前cookie值                     传入商品id               最终cookie值
     *      null或没有prodHist          1                     1    (算法: 直接返回传入的id )
     *             1                  2                     2,1 (没有重复且小于3个。算法:直接把传入的id放最前面 )
     *             2,1                1                     1,2(有重复且小于3个。算法:去除重复id,把传入的id放最前面 )
     *             3,2,1              2                     2,3,1(有重复且3个。算法:去除重复id,把传入的id放最前面)
     *             3,2,1              4                     4,3,2(没有重复且3个。算法:去最后的id,把传入的id放最前面)
     */
    public String createValue(HttpServletRequest request,String id){
        Cookie[] cookies = request.getCookies();
        String historypro = null;
        if(cookies!=null){
            for(Cookie c:cookies){
                if(c.getName().equals("historypro")){
                    historypro = c.getValue();
                    break;
                }
            }
        }
        if(cookies==null||historypro==null){
            return id;
        }
        //historypro.contains(id);这种方法不对,原因:id数据类型为String,如果有一个id值为21,同样包含2
        //String -> String[] ->  Collection :为了方便判断重复id
        String[] ids = historypro.split(",");
        Collection colls = Arrays.asList(ids); //<3,21>
        // LinkedList 方便地操作(增删改元素)集合
        // Collection -> LinkedList
        LinkedList list = new LinkedList(colls);
        //不超过3个
        if(list.size()<3){
            //id重复
            if(list.contains(id)){
                //去除重复id,把传入的id放最前面
                list.remove(id);
                list.addFirst(id);
            }else{
                //直接把传入的id放最前面
                list.addFirst(id);
            }
        }else{
            //等于3个
            //id重复
            if(list.contains(id)){
                //去除重复id,把传入的id放最前面
                list.remove(id);
                list.addFirst(id);
            }else{
                //去最后的id,把传入的id放最前面
                list.removeLast();
                list.addFirst(id);
            }
        }
        // LinedList -> String 
        StringBuffer sb = new StringBuffer();
        for (Object object : list) {
            sb.append(object+",");
        }
        //去掉最后的逗号
        String result = sb.toString();
        result = result.substring(0, result.length()-1);
        return result;
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}
    
  • 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

2)效果: 
a)首次访问: 

b)详细内容: 

c)多次访问: 

版权声明:本文为博主原创文章,未经博主允许不得转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值