java(16)--利用cookie显示商品浏览历史

本文介绍了一个使用Servlet实现的双页面程序,分别展示商品和浏览历史,并通过Cookie记录用户浏览过的商品。

本程序分为两个页面,用Servlet实现

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

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.print("本网站有以下商品:");
        Map<String, Book> map=Db.getAll();
        for(Map.Entry<String, Book> entry:map.entrySet()){
            Book book=entry.getValue();
            out.print("<a href='/aDay07/servlet/CookieDemo4?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>");
        }
        out.print("<br/>");

        //显示出曾经浏览过的商品
        out.print("您曾经浏览过:<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=(Book)Db.getAll().get(id);
                    out.print(book.getName()+"<br/>");
                }
            }
        }

    }


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

}

class Db{
    private static Map<String,Book> map=new LinkedHashMap<String,Book>();
    static{
        map.put("1", new Book("1","HeadFirst Java","Sierra&Bates",79));
        map.put("2", new Book("2","jdbc开发","张三",39));
        map.put("3", new Book("3","spring开发","李四",39));
        map.put("4", new Book("4","hibernate开发","王五",39));
        map.put("5", new Book("5","ajax开发","赵六",39));
    }
    public static Map getAll(){
        return map;
    }
}


class Book{
    private String id;
    private String name;
    private String author;
    private double price;

    public Book() {
        super();
    }
    public Book(String id, String name, String author, double price) {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
    }

    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 double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
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;

//显示商品详细信息并将商品信息增加到cookie里面
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();

        // 显示用户点击查看的商品
        String id = request.getParameter("id"); // 获取url中所带的参数
        Book book = (Book) Db.getAll().get(id);

        out.print("您所要查看书的详细信息:<br/>");
        out.print(book.getId() + "<br/>");
        out.print(book.getName() + "<br/>");
        out.print(book.getAuthor() + "<br/>");
        out.print(book.getPrice() + "<br/>");

        // 将用户浏览过的书的id号以cookie形式回写给用户浏览器
        String bookHistory = buildBookHistory(request, id);
        Cookie cookie = new Cookie("bookHistory", bookHistory);
        cookie.setMaxAge(3000);
        cookie.setPath("/aDay07");
        response.addCookie(cookie);

    }

    // 构建发送给浏览器的cookie值
    private String buildBookHistory(HttpServletRequest request, String id) {
        // 分以下几种情况
        // 原有串式 新看书籍id 形成的新的串式
        // bookHistory "" 1 bookHistory=1
        // bookHistory 3_1_5 1 bookHistory=1_3_5
        // bookHistory 3_2_5 1 bookHistory=1_3_2
        // bookHistory 5_2 1 bookHistory=1_5_2

        String bookHistory = null;
        // 获得原有bookHistory串式
        Cookie cookies[] = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie.getName().equals("bookHistory")) {
                bookHistory = cookie.getValue();
            }
        }

        //          原有串式 新看书籍id 形成的新的串式
        // bookHistory "" 1 bookHistory=1
        if(bookHistory==null){
            bookHistory = id;
            return bookHistory;
        }

        //bookHistory        3_1_5      1      bookHistory=1_3_5
        LinkedList<String> list = new LinkedList(Arrays.asList(bookHistory.split("\\_")));
        if(list.contains(id)){
            list.remove(id);
            list.addFirst(id);
        }else{
            //bookHistory        3_2_5      1      bookHistory=1_3_2
            if(list.size()>=3){
                list.removeLast();
                list.addFirst(id);
            }else{
                //bookHistory        5_2        1      bookHistory=1_5_2
                list.addFirst(id);
            }
        }

        //增加格式
        StringBuffer sb = new StringBuffer();
        for(String bid : list){
            sb.append(bid + "_");
        }

        //调整格式:1_3_2_
        bookHistory = sb.deleteCharAt(sb.length()-1).toString();
        return bookHistory;
    }

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

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值