博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Cookie记录浏览记录
阅读量:6831 次
发布时间:2019-06-26

本文共 4825 字,大约阅读时间需要 16 分钟。

package cookie.test;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

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 CookieDemo3 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html);charset=UTF-8");
        PrintWriter out = response.getWriter();
       
        //输出网站商品
        out.write("本网站有如下书籍:<br/>");
        Map<String,Book> map = Db.getAll();
        for(Map.Entry<String,Book>entry:map.entrySet()) {
            Book book = entry.getValue();
            out.println("<a href='/cookie/servlet/CookieDemo4?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>");
           
        }
       
        //2,显示用户看过的商品
        out.print("<br/>您曾经浏览过的商品:<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) {
                    Book book = Db.getAll().get(id);
                    out.print(book.getName()+"<br/>");
                }
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

    }

   

}

class Db{

    //private Map map = new HashMap();
    private static Map<String,Book> map = new LinkedHashMap<String,Book>();
    static {
        map.put("1",new Book("1","水浒传","施耐庵","名著"));
        map.put("2",new Book("2","三国演义","罗贯中","名著"));
        map.put("3",new Book("3","西游记","吴承恩","名著"));
        map.put("4",new Book("4","红楼梦","曹雪芹","名著"));
        map.put("5",new Book("5","文章中含有违禁内容: 金!瓶!梅!","笑笑生","名著"));
    }
   
    public static Map<String, Book> 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;
    }

}

 

 

 

 

 

 

 

 

 

package cookie.test;

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;
//显示商品详细信息的servlet
public class CookieDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html);charset=UTF-8");
        PrintWriter out = response.getWriter();

        //根据用户带过来的id,显示相应商品的详细信息

        String id = request.getParameter("id");
        Book book = (Book)Db.getAll().get(id);
        out.write(book.getId() + "<br/>");
        out.write(book.getName() + "<br/>");
        out.print(book.getAuthor() + "<br/>");/
        out.write(book.getDescription() + "<br/>");
       
        //构建cookie
        String cookieValue= buildCookie(id,request);
        Cookie cookie = new Cookie("bookHistory",cookieValue);
       
        cookie.setMaxAge(3600*24*30);
        cookie.setPath("/cookie");
       
        response.addCookie(cookie);
       
    }

    private String buildCookie(String id, HttpServletRequest request) {

        //bookHistory = null

       
        String bookHistory = null;
        Cookie cookies[] = request.getCookies();
        for(int i=0;cookies!=null&&i<cookies.length;i++) {
            if(cookies[i].getName().equals("bookHistory"));
                bookHistory = cookies[i].getValue();
               
        }
       
        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);
        }
        list.addFirst(id);
       
        StringBuffer sb = new StringBuffer();
        for(String bid : list) {
            sb.append(bid + ",");
        }
        return sb.deleteCharAt(sb.length()-1).toString();
       
       
       
       
       
       
        /*Cookie cookie[] = request.getCookies();
        for(Cookie c:cookie) {
            if(c.getName().equals("bookHistory")) {
               
                String str = c.getValue();
                if(str.matches(".+"+id+".+")) {
                    str = str.replace(",?"+id+",?",",");
                    str = str + id;
                }else {
                    str = str+","+id;
                }
                return str;
            }
        }

        return id;*/

    }

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

    }

}

转载地址:http://kftkl.baihongyu.com/

你可能感兴趣的文章
移动web开发常用JavaScript代码(转)
查看>>
学习 地图
查看>>
++的实验
查看>>
linux的环境变量
查看>>
编译安装GCC 4.7.2
查看>>
PAT 乙级 1045. 快速排序(25)
查看>>
高性能mysql:创建高性能的索引
查看>>
node.js的net模块实现socket通信
查看>>
Windows应用程序的VC链接器设置
查看>>
用TCP/IP实现自己简单的应用程序协议:最后再返回来看HTTP协议
查看>>
【转】IBM Rational Rose 操作指南(上)
查看>>
【转】linux 查看进程启动路径
查看>>
菜鸟学习WPF(一):开篇
查看>>
基于人脸识别的商业大数据9
查看>>
Hibernate查询HQL(第二部分)
查看>>
数据源配置
查看>>
闲置的2017
查看>>
【习题1】第一个程序【第2天】
查看>>
JavaScript 编程模式
查看>>
c#获取文件夹路径(转载)
查看>>