java-Cookie的练习

用户浏览过的商品

Product.java

package 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();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Product [id=" + id + ", proName=" + proName + ", proType=" + proType + ", price=" + price + "]";
    } 
}

ProductDao.java

package dao;

import java.util.ArrayList;
import java.util.List;

import entity.Product;

/*
 * 该类中存放Product对象的增删改查方法
 * */

public class ProductDao {
    //模拟"数据库",存放所有商品数据
    private static List<Product> data = new ArrayList<Product>();

    /*
     * 初始化商品数据
     * */
    static{
        //只执行一次
        for(int i=1;i<10;i++){
            data.add(new Product(""+i,"笔记本"+i,"LN00"+i,34.0+i));
        }
    }


    /*
     * 提供查询所有商品的方法
     * */
    public List<Product> findAll(){
        return data;
    }

    /*
     * 根据编号查询商品的方法
     * */
    public Product findById(String id){
        for(Product p:data){
            if(p.getId().equals(id)){
                return p;
            }
        }
        return null;
    }
}

DatailServlet.java

package servlet;

import dao.ProductDao;
import entity.Product;

/*
 * 显示商品详细
 * */

@SuppressWarnings("serial")
public class DatailServlet extends HttpServlet {


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

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        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>");

        //1.获取编号
        String id = request.getParameter("id");

        //2.到数据库中查询对应编号的商品
        ProductDao dao = new ProductDao();
        Product product = dao.findById(id); 

        //3.显示到浏览器
        String html = "";
        html += "<table border='1' align='center' width='600px'>";

        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>";

        out.print(html);

        /*
         * 创建cookie,并发送
         * */
        //1.创建cookie
        Cookie cookie = new Cookie("prodHist",createValue(request, id));
        cookie.setMaxAge(1*30*24*60*60);

        //2.发送cookie
        response.addCookie(cookie);



        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }

private String createValue(HttpServletRequest request,String id) {

        Cookie[] cookies = request.getCookies();
        String prodHist = null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("prodHist")){
                    prodHist = cookie.getValue();
                    break;
                }
            }
        }

        // null或没有prodHist
        if(cookies==null || prodHist==null){
            //直接返回传入的id
            return id;
        }

        // 3,21          2
        //String -> String[] ->  Collection :为了方便判断重复id
        String[] ids = prodHist.split(",");
        Collection<String> colls = Arrays.asList(ids); //<3,21>
        // LinkedList 方便地操作(增删改元素)集合
        // Collection -> LinkedList
        LinkedList<String> list = new LinkedList<String>(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 {

        doGet(request, response);
    }
}

ListServlet.java

package servlet;

import dao.ProductDao;
import entity.Product;

/*
 * 查询所有商品的servlet
 * */

@SuppressWarnings("serial")
public class ListServlet extends HttpServlet {

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

        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        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>");

        //1.读取数据库,查询商品列表
        ProductDao dao = new ProductDao();
        List<Product> list = dao.findAll();

        //2.把商品显示到浏览器
        String html = "";
        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>";
                ///day11_web/DatailServlet?id=1 访问DetailServlet的servlet程序,同事传递名为id,值为1的参数
                html += "<td>"+p.getId()+"</td><td><a href='"+request.getContextPath()+"/DatailServlet?id="+p.getId()+"'>"+p.getProName()+"</a></td><td>"+p.getProType()+"</td><td>"+p.getPrice()+"</td>";
                html += "</tr>";
            }
        }


        html += "</table>";

        /**
         * 显示浏览过的商品
         */
        html += "最近浏览过的商品:<br/>";
        //取出prodHist的cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("prodHist")){
                    String prodHist = cookie.getValue(); // 3,2,1
                    String[] ids = prodHist.split(",");
                    //遍历浏览过的商品id
                    for (String id : ids) {
                        //查询数据库,查询对应的商品
                        Product p = dao.findById(id);
                        //显示到浏览器
                        html += ""+p.getId()+"&nbsp;"+p.getProName()+"&nbsp;"+p.getPrice()+"<br/>";
                    }
                }
            }
        }

        out.print(html);
        out.println("  </BODY>");
        out.println("</HTML>");
        out.flush();
        out.close();
    }


    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、付费专栏及课程。

余额充值