javaweb圖書商城設計之購物車模塊(3)。本站提示廣大學習愛好者:(javaweb圖書商城設計之購物車模塊(3))文章只能為提供參考,不一定能成為您想要的結果。以下是javaweb圖書商城設計之購物車模塊(3)正文
本文持續為大家分享了javaweb圖書商城中購物車模塊,供大家參考,詳細內容如下
購物車存儲
保管在session中
保管在cookie中
保管在數據庫中
1、創立相關類
購物車的構造:
CartItem:購物車條目,包括圖書和數量
Cart:購物車,包括一個Map
/**
* 購物車類
*/
public class Cart {
private Map<String,CartItem> map = new LinkedHashMap<String,CartItem>();
/**
* 計算算計
* @return
*/
public double getTotal() {
// 算計=一切條目的小計之和
BigDecimal total = new BigDecimal("0");
for(CartItem cartItem : map.values()) {
BigDecimal subtotal = new BigDecimal("" + cartItem.getSubtotal());
total = total.add(subtotal);
}
return total.doubleValue();
}
/**
* 添加條目到車中
* @param cartItem
*/
public void add(CartItem cartItem) {
if(map.containsKey(cartItem.getBook().getBid())) {//判別原來車中能否存在該條目
CartItem _cartItem = map.get(cartItem.getBook().getBid());//前往原條目
_cartItem.setCount(_cartItem.getCount() + cartItem.getCount());//設置老條目的數量為,其自己數量+新條目的數量
map.put(cartItem.getBook().getBid(), _cartItem);
} else {
map.put(cartItem.getBook().getBid(), cartItem);
}
}
/**
* 清空一切條目
*/
public void clear() {
map.clear();
}
/**
* 刪除指定條目
* @param bid
*/
public void delete(String bid) {
map.remove(bid);
}
/**
* 獲取一切條目
* @return
*/
public Collection<CartItem> getCartItems() {
return map.values();
}
}
/**
* 購物車條目類
*
*/
public class CartItem {
private Book book;// 商品
private int count;// 數量
/**
* 小計辦法
* @return
* 處置了二進制運算誤差問題
*/
public double getSubtotal() {//小計辦法,但它沒有對應的成員!
BigDecimal d1 = new BigDecimal(book.getPrice() + "");
BigDecimal d2 = new BigDecimal(count + "");
return d1.multiply(d2).doubleValue();
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
2、添加購物車條目

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>購物車列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
* {
font-size: 11pt;
}
div {
margin:20px;
border: solid 2px gray;
width: 150px;
height: 150px;
text-align: center;
}
li {
margin: 10px;
}
#buy {
background: url(<c:url value='/images/all.png" />
4、刪除購物車條目

5、我的購物車
top.jsp中存在一個鏈接:我的購物車
我的購物車直接訪問/jsps/cart/list.jsp,它會顯示session中車的一切條目。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支持。