- 這里的購物車暫時存放書,后期把參數改成Object,把方法抽取成接口,只要實現了接口的Object類都可以放進購物項,這樣就實現了購物任何物品
- 使用購物項因為一個購物項可以包含某種商品的數量,總價等,反之則需要把商品重復存放到購物車,沒有用戶體驗
- 購物車用HashMap,鍵存放書id,值存放購物項
1. 設計bean
書
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 + "]";
}
}
購物項
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 + "]";
}
}
購物車
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. 購物車序列化存放到Cookie
2.1 模仿購物車添加商品
//往購物車添加書本
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
- 其中Cookie不能有[ ] ( ) = , " / ? @ : ;特殊字符,需要URL編碼
- ByteArrayOutputStream.toString()把字節數組內容轉化成字符串
// -----------------------------購物車對象序列化------------------------[開始]
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. 服務器讀取Cookie
- 遍歷所有Cookie,找到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. 測試結果
CartItem [book=Book [id=1, name=且聽風吟, price=10.5], quantity=2, price=0.0]
<!-- 剩下且聽風吟 * 2 -->