package de.bvb.cookie;

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

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

/**
 * 显示商品列表和已经浏览过的商品
 *
 * @author joker
 *
 */
public class CookieDemo11 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/>");
        for (Entry<String, Book> b : Db.getBooks().entrySet()) {
            out.write("<a target='_blank' href='/web/CookieDemo12?id="
                    + b.getKey() + "'>" + b.getValue().getName() + "</a><br/>");
        }

        // 显示浏览过的商品
        out.write(" <br/> <br/>浏览过的商品: <br/>");
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("history")) {
                String[] ids = cookies[i].getValue().split("\\,");
                for (String s : ids) {
                    out.write(Db.getBooks().get(s).getName() + "<br/>");
                }
            }
        }
    }

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

        doGet(request, response);
    }
}

class Db {
    private static LinkedHashMap<String, Book> books = new LinkedHashMap<String, Book>();
    static {
        books.put("1", new Book("1", "javaWeb", "javaweb"));
        books.put("2", new Book("2", "android", "android"));
        books.put("3", new Book("3", "spring", "spring"));
        books.put("4", new Book("4", "strus", "strus"));
        books.put("5", new Book("5", "ios", "ios"));
    }

    public static Map<String, Book> getBooks() {
        return books;
    }
}

class Book {
    private String id;
    private String name;
    private String description;

    public Book(String id, String name, String description) {
        super();
        this.id = id;
        this.name = name;
        this.description = description;
    }

    public Book() {
        super();
    }

    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 getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}
package de.bvb.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.Map.Entry;

import javax.enterprise.inject.ResolutionException;
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 javax.swing.text.DateFormatter;

/**
 * 显示商品详情
 *
 * @author joker
 *
 */
public class CookieDemo12 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/>");
        String id = request.getParameter("id");
        for (Entry<String, Book> b : Db.getBooks().entrySet()) {
            if (id.equals(b.getKey())) {
                out.write(b.getValue().getId() + "<br/>");
                out.write(b.getValue().getName() + "<br/>");
                out.write(b.getValue().getDescription() + "<br/>");
            }
        }

        // 回写cookie,保存最后浏览的商品id
        String history = buildIds(id, request);
        Cookie cookie = new Cookie("history", history);
        cookie.setMaxAge(1 * 30 * 24 * 60 * 60);
        cookie.setPath("/web");
        response.addCookie(cookie);
    }

    private String buildIds(String id, HttpServletRequest request) {
        String history = null;
        Cookie[] cookies = request.getCookies();
        for (int i = 0; cookies != null && i < cookies.length; i++) {
            if (cookies[i].getName().equals("history")) {
                history = cookies[i].getValue();
            }
        }
        if (history == null) {
            return id;
        }
        LinkedList<String> ids = new LinkedList<String>(Arrays.asList(history
                .split("\\,")));
        if (ids.contains(id)) {
            ids.remove(id);
        } else {
            if (ids.size() >= 3) { // 最多显示3条浏览历史
                ids.removeLast();
            }
        }
        ids.addFirst(id);
        StringBuffer sb = new StringBuffer();
        for (String s : ids) {
            sb.append(s).append(",");
        }
        return sb.deleteCharAt(sb.length() - 1).toString();
    }

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

        doGet(request, response);
    }

}

javaWeb 使用cookie显示商品浏览记录的更多相关文章

  1. Cookie实现商品浏览记录--方式二:JS实现

    使用Cookie实现商品浏览记录:方式二:JS方法实现cookie的获取以及写入.当某一个产品被点击时,触发JS方法.利用JS方法判断一下,此产品是否在浏览记录中.如果不存在,则将产品ID加入到coo ...

  2. 使用Cookie保存商品浏览记录

    数据流程:页面上是商品列表,点击<a href="productServlet">商品名</a> ==>跳转到自定义的servlet中进行处理,先得到 ...

  3. Cookie实现商品浏览记录--方式一:Java实现

    方式一:Java代码方式实现:此种方式实现思路较为顺畅.难点在于,如何实现将最近浏览的产品显示在最前面:实现方式是借助LinkedList提供的remove()方法,先将此id从列表中移除,然后再借助 ...

  4. Java遇见HTML——JSP篇之商品浏览记录的实现

    一.项目总体介绍 使用Cookie实现商品浏览记录. 要实现这个程序采取的是Model1(Jsp+JavaBean)架构实现,具体步骤: 首先要有个数据库,商品表,操作数据库的一个类DBHelper类 ...

  5. (JS实现顾客商品浏览记录以及购物车)Cookie的保存与删除

    //JS实现顾客浏览商品的记录以及实现购物车的功能function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.s ...

  6. 使用cookie实现打印浏览记录的功能

    可以用cookie知识来实现打印浏览记录.这里面用到的思路是将浏览记录以字符串的方式保存到cookie中,当浏览记录增加时,再将其转化为数组. $uri=$_SERVER['REQUEST_URI'] ...

  7. Cookie案例-显示商品浏览历史纪录

    package cn.itcast.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.D ...

  8. javaWeb 使用cookie显示上次访问网站时间

    package de.bvb.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.Date ...

  9. Cookie中图片的浏览记录与cookie读取servle时路径的设置(文字描述)

    public class ShowServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpSer ...

随机推荐

  1. iOS快速集成友盟社会化分享功能(v6.1.1)

    1.  U-Share SDK集成 1.1 下载U-Share SDK 通过iOS社会化组件选择所需的社交平台后进行下载,下载链接http://dev.umeng.com/social/ios/sdk ...

  2. [css]我要用css画幅画(八) - Hello Kitty

    接着之前的[css]我要用css画幅画(七) - 哆啦A梦,这次画的是Hello Kitty. /* 开始前先说点废话, 一转眼就2016年了,过完年后一直没更新博客,无他,就是懒得动. 这一转眼,一 ...

  3. php无法创建中文名的文件

    需要使用iconv强制转换后才可以.

  4. QT 数据库编程四

    //vmysql.cpp #include "vmysql.h" #include <QMessageBox> Vmysql::Vmysql() { mysql_ini ...

  5. poj2186 强连通缩点

    Popular Cows Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 29773   Accepted: 12080 De ...

  6. ASP.NET MVC Web API 学习笔记---第一个Web API程序

    http://www.cnblogs.com/qingyuan/archive/2012/10/12/2720824.html GetListAll /api/Contact GetListBySex ...

  7. 推荐一款免安装的在线Visio流程工具ProcessOn

    昨天收到一人的邮件,说某个软件叫ProcessOn是web版的visio,出于对技术知识的渴望以及自己的好奇所以对ProcessOn进行了一番体验.结果有点被这个软件给吸引上了,无论是在用户体验上,还 ...

  8. PE文件结构

    PE头 typedef struct _IMAGE_NT_HEADERS { DWORD Signature; PE头标识 为固定的ascii码 PE\\ IMAGE_FILE_HEADER File ...

  9. Mysql 格式化日期格式

    DATE_FORMAT(date, format) 根据格式串format 格式化日期或日期和时间值date,返回结果串. 可用DATE_FORMAT( ) 来格式化DATE 或DATETIME 值, ...

  10. SSH Spring3\Java1.8 “Unable to instantiate Action, xxAction, defined for &#39;xxAction_login&#39; in namespace &#39;/&#39;null”

    1.Stacktraces Unable to instantiate Action,xxAction, defined for 'xxAction_login' in namespace '/'nu ...