Cookie realize cart function



  • Here's cart to temporarily store books, late into the Object parameter, the method to extract the interface, as long as the realization of the Object class interface can be put shopping items, so to achieve any items shopping
  • Use shopping item because a number of shopping items can contain a commodity, such as the total price, otherwise you need to make repeated storage of goods to cart, not the user experience
  • Shopping cart with HashMap, key deposit book id, value store shopping items


1. Design bean

book

public class Book implements Serializable{
    
    //因为对象传输需要实现序列化接口
    //后面代码中id作为Map的键,而键只能为String
    String id;
    String name;
    double price;
    
    public Book(String id, String name, double price) {
        this.id = id;
        this.name = name;
        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 double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book [id=" + id + ", name=" + name + ", price=" + price + "]";
    }
}

Shopping items

public class CartItem implements Serializable{
    
    private Book book;
    private int quantity;
    private double price;
    
    public Book getBook() {
        return book;
    }
    public void setBook(Book book) {
        this.book = book;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }
    public double getPrice() {
        return book.getPrice() * quantity;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    
    @Override
    public String toString() {
        return "CartItem [book=" + book + ", quantity=" + quantity + ", price=" + price + "]";
    }
}

shopping cart

public class Cart<K, V> implements Serializable{

    //键为书名id,储存实物
    private double totalPrice;
    private HashMap<String,CartItem> bookMap = new HashMap<String, CartItem>();
    
    public void addBook(Book book){
        //从购物车找对应书籍的购物项
        CartItem cartItem = bookMap.get(book.getId());
        //若没有该书的购物项,新建一个
        if(cartItem == null){
            cartItem = new CartItem();
            cartItem.setBook(book);
            cartItem.setQuantity(1);
            bookMap.put(book.getId(), cartItem);
        }else{
            cartItem.setQuantity(cartItem.getQuantity() + 1);
        }
    }
    public void deleteBook(Book book){
        CartItem cartItem = bookMap.get(book.getId());
        if(cartItem == null){
            //do nothing
        }else if(cartItem.getQuantity() == 1){
            bookMap.remove(book.getId());
        }else{
            cartItem.setQuantity(cartItem.getQuantity() - 1);
        }
    }
    public double getPrice(){
        //遍历购物车里的购物项
        for(Map.Entry set : bookMap.entrySet()){
            //String bookId = (String) set.getKey();
            CartItem cartItem = (CartItem) set.getValue();
            totalPrice += cartItem.getPrice();
        }
        return totalPrice;
    }

    public HashMap<String, CartItem> getBookMap() {
        return bookMap;
    }
    public void setBookMap(HashMap<String, CartItem> bookMap) {
        this.bookMap = bookMap;
    }
    public double getTotalPrice() {
        return totalPrice;
    }
    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }
}




2. serialized store to cart Cookie


2.1 imitate cart add items

//往购物车添加书本
Cart cart = new Cart();
cart.addBook(new Book("1","且听风吟",10.5f));
cart.addBook(new Book("1","且听风吟",10.5f));
cart.addBook(new Book("1","且听风吟",10.5f));
cart.addBook(new Book("2","我们仨",5.5f));
cart.deleteBook(new Book("1","且听风吟",10.5f));
cart.deleteBook(new Book("2","我们仨",5.5f));
cart.deleteBook(new Book("3","解忧杂货店",20.5f));


2.2 Cookie from the car into a sequence of

  • Cookie which can not have [] () = "/ @:;? Special characters, you need to encode URL
  • ByteArrayOutputStream.toString () byte array content into a string
//  -----------------------------购物车对象序列化------------------------[开始]
ByteArrayOutputStream bos= new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(cart);
String objectString = URLEncoder.encode(bos.toString("ISO-8859-1"),"UTF-8");
//  -----------------------------购物车对象序列化------------------------[完]    

//  -----------------------------给客户端添加cookie------------------------[开始]
response.setContentType("text/html;charset=UTF-8");
Cookie cookie = new Cookie("name", objectString);
cookie.setMaxAge(1000);
response.addCookie(cookie);
//  -----------------------------给客户端添加cookie------------------------[完]




3. The server reads the Cookie

  • Through all the Cookie, find Cart
Cookie[] cookies = request.getCookies();
if(cookies != null){
    for(Cookie cookieLoop : cookies){
        String name = cookieLoop.getName();
        String value = URLDecoder.decode(cookieLoop.getValue(), "UTF-8");
        if(name == "Cart"){
            ByteArrayInputStream bis = new ByteArrayInputStream(value.getBytes("ISO-8859-1"));
            ObjectInputStream ois = new ObjectInputStream(bis);
            try {
                Cart cart1 = (Cart) ois.readObject();
                HashMap cartMap = cart1.getBookMap();
                for(Object cartItem : cartMap.values()){
                    //遍历购物项并打印
                    System.out.println(cartItem.toString());
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}




4. Test results

CartItem [book=Book [id=1, name=且听风吟, price=10.5], quantity=2, price=0.0]
<!-- 剩下且听风吟 * 2 -->




Guess you like

Origin www.cnblogs.com/Howlet/p/12071217.html