模擬購物車

一個購物車的demo,數(shù)據(jù)時死的笔诵。用mvc結(jié)構(gòu)寫
QQ截圖20170627220828.png

上面的是購物車中的結(jié)構(gòu)目錄
首先建立數(shù)據(jù)源 用死數(shù)據(jù)進行模擬

/**
 * 模擬數(shù)據(jù)庫的數(shù)據(jù)
 */
public class MyDb {
    private static Map<String, Book> map=new LinkedHashMap();
    static{
        map.put("1", new Book("1","javaweb開發(fā)","老張",20,"一本經(jīng)典的書"));
        map.put("2", new Book("2","jdbc開發(fā)","李勇",30,"一本jdbc的書"));
        map.put("3", new Book("3","spring開發(fā)","老黎",50,"一本相當(dāng)經(jīng)典的書"));
        map.put("4", new Book("4","hibernate開發(fā)","老佟",56,"一本佟佟的書"));
        map.put("5", new Book("5","struts開發(fā)","老畢",40,"一本經(jīng)典的書"));
        map.put("6", new Book("6","ajax開發(fā)","老張",50,"一本老張的書"));
    }
    
    /**
     * 得到所有的書本的信息
     * @return
     */
    public static Map<String, Book> getAll() {
        return map;
    }
}

書本的實體類

/**
 * 書的實體類
 */
public class Book {
    private String id;
    private String name;
    private String author;
    private double price;
    private String description;
    
    public Book() {
        // TODO Auto-generated constructor stub
    }
    
    public Book(String id, String name, String author, double price, String description) {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
        this.description = description;
    }
    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 getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

接下來是 Dao

/**
 * 根據(jù) 需求來和 數(shù)據(jù)庫 打交道
 */
public class BookDao {
    
    /**
     * 根據(jù)book的id來獲取書
     */
    public Book find(String id){
        return  MyDb.getAll().get(id);
    }
    
    /**
     * 獲取所有的書本信息 以map的方式給你
     */
    public Map getAll(){
        return MyDb.getAll();
    }
}

業(yè)務(wù)處理類

/**
 * 書本業(yè)務(wù)的邏輯   用于和 dao層 和 view進行交互數(shù)據(jù)
 */
public class BusinessService {

    BookDao bookDao=new BookDao();
    
    /**
     * 得到所有的書本信息
     * @return
     */
    public Map getAll(){
        return bookDao.getAll();
    }
    
    /**
     * 買書
     */
    public void buybook(String bookid, Cart cart) {
        Book book = bookDao.find(bookid);
        cart.add(book);
    }
    
    /**
     * 清空購物車
     * @param cart
     * @throws CartNotFoundException 
     */
    public void clear(Cart cart) throws CartNotFoundException{
        if (cart ==null) {
            throw new CartNotFoundException();
        }
        cart.clear();
    }
    
    /**
     * 刪除購物車中的商品
     * @param cart
     * @param bookid
     * @throws CartNotFoundException
     */
    public void delete(Cart cart,String bookid) throws CartNotFoundException{
        if(cart==null){
            throw new CartNotFoundException();
        }
        cart.getMap().remove(bookid);
    }
    
    /**
     * 將 商品的數(shù)量進行改變
     * @param cart
     * @param bookid
     * @param quantity
     */
    public void updateCart(Cart cart,String bookid,int quantity) throws CartNotFoundException{
        if(cart==null){
            throw new CartNotFoundException();
        }
        CartItem cartItem=cart.getMap().get(bookid);
        cartItem.setQuantity(quantity);
    }
}

展示書本列表的 servlet

 /**
  * 書本的列表頁
  */
public class ListBookServlet extends HttpServlet {
     
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //將數(shù)據(jù)中的書本信息取出  給request 域中 方便jsp中調(diào)用顯示
        BusinessService businessService=new BusinessService();
        Map<String, Book> map=businessService.getAll();
        request.setAttribute("map", map);
        request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response);
    }

 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

展示書本的jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>書本的列表</title>
</head>
<body style="text-align: center;">
         <br/>
    <h2>書籍列表</h2>
    <br/><br/>
    
    <table border="1" width="80%">
        <tr>
            <td>書籍編號</td>
            <td>書名</td>
            <td>作者</td>
            <td>售價</td>
            <td>描述</td>
            <td>操作</td>
        </tr>
        
        <%-- Set<Map.Entry<String,Book>>  每次循環(huán)出來的就是這個--%> 
        <c:forEach var="me" items="${map}">
        <tr>
            <td>${me.key}</td>
            <td>${me.value.name}</td>
            <td>${me.value.author}</td>
            <td>${me.value.price}</td>
            <td>${me.value.description}</td>
            <td>
                <a href="${pageContext.request.contextPath}/BuyServlet?bookid=${me.key}">購買</a>
            </td>
        </tr>
        </c:forEach>
         
    </table>
</body>
</html>

購買書本后的servlet

/**
 *  點擊購買按鈕調(diào)到此界面進行處理
 */
public class BuyServlet extends HttpServlet {
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         String bookid=request.getParameter("bookid");
         
         Cart cart=(Cart) request.getSession().getAttribute("cart");
         if (cart==null) {
            cart=new Cart();
            request.getSession().setAttribute("cart", cart);
        }
         //將商品加入購物車中 
         BusinessService businessService=new BusinessService();
         businessService.buybook(bookid, cart);
         //展示購買過的商品
         request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    }

     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

展示購買的商品的 servlet

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>購買過的商品</title>
<script type="text/javascript">
    /*  清空購物車  */
    function clearcart() {
        var isClear=window.confirm("您確定要清空購物車嗎眉踱?诞吱?");
        if(isClear){
            window.location.href="${pageContext.request.contextPath}/ClearCartServlet";
        }
    }
    
    /*更新 顯示的數(shù)據(jù)*/
    function updateCart(input, id){
        // input 輸入的內(nèi)容   id 是更新的是哪個 商品
        var quantity=input.value;
        var b = window.confirm("請確認(rèn)改為:" + quantity);
        if(b) {
            /* 將修改 的構(gòu)成車中商品的id和修改成的數(shù)量給servlet  */
            window.location.href="${pageContext.request.contextPath}/UpdateCartServlet?bookid="+id + "&quantity=" + quantity;
         }  
    }

</script>
</head>
 <body style="text-align: center;">
    <br/>
    <h2>購物車列表</h2>
    <br/><br/>
    <!-- 當(dāng)購物車不是空 -->
    <c:if test="${!empty(cart.map)}">
        <table border="1" width="80%">
            <tr>
                <td>書名</td>
                <td>作者</td>
                <td>單價</td>
                <td>數(shù)量</td>
                <td>小計</td>
                <td>操作</td> 
            </tr>
            
            <!-- Set<Map.Entry<String,CarItem>>  每次循環(huán)出來的就是這個  -->
           <c:forEach var="me" items="${cart.map }">
               <tr>
                    <td>${me.value.book.name}  </td>
                    <td>${me.value.book.author}  </td>
                    <td>${me.value.book.price}  </td>
                    <td>
                        <input type="text" name="quantity" value="${me.value.quantity}"  style="width: 60px" onchange="updateCart(this,${me.value.book.id })">
                    </td>
                    <td>${me.value.quantity}  </td>
                    <td>${me.value.price }</td>
                    <td>
                        <a href="${pageContext.request.contextPath}/DeleteServlet?bookid=${me.value.book.id}">刪除</a>
                    </td>
                </tr>
           </c:forEach>
           
        <tr>
            <td colspan="2">
                <a href="javascript:clearcart()">清空購物車</a>
            </td>
            <td colspan="2">合計</td>
            <td colspan="2">${cart.price}</td>
        </tr>
           
         </table>
    </c:if> 
    
    <c:if test="${empty(cart.map)}">
          對不起慈参,您還沒有購買任何商品
    </c:if>
    
</body>
</html>

清空購物車的 servlet

/**
 * 清空購物車哦
 */
public class ClearCartServlet extends HttpServlet {
     
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cart cart= (Cart) request.getSession().getAttribute("cart");
        BusinessService businessService=new BusinessService();
        try {
            businessService.clear(cart);
            request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
        } catch (CartNotFoundException e) {
             request.setAttribute("message","對不起,您還沒有購買任何商品!!!");
             request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

刪除 商品的 sevlet

/**
 *  刪除 購物列表中的數(shù)據(jù)
 */
public class DeleteServlet extends HttpServlet {
 
     
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookid=request.getParameter("bookid");
        //將次數(shù)的id從購物車進行刪除
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        BusinessService businessService=new BusinessService();
        try {
            businessService.delete(cart, bookid);
            request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); 
        } catch (CartNotFoundException e) {
             request.setAttribute("message","對不起备绽,您還沒有購買任何商品!!!");
             request.getRequestDispatcher("/message.jsp").forward(request, response); 
        }
    }

     
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

當(dāng)在購買過的商品中進行修改商品的數(shù)量的時候

/**
 * 當(dāng)修改購買商品的數(shù)量 進行操作的 servlet
 */
public class UpdateCartServlet extends HttpServlet {
     
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
         String bookid=request.getParameter("bookid");
         String quantity=request.getParameter("quantity");
         BusinessService businessService=new BusinessService();
         Cart cart=(Cart)request.getSession().getAttribute("cart");
         int q=Integer.parseInt(quantity);
         try {
            businessService.updateCart(cart, bookid, q);
            request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response); 
        } catch (CartNotFoundException e) {
             request.setAttribute("message","對不起,您還沒有購買任何商品!!!");
             request.getRequestDispatcher("/message.jsp").forward(request, response); 
        }
         
         
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

購物車的實體

/**
 * 購物車
 */
public class Cart {
    
    /**
     * 用于存儲 購車車中的信息   key--- id   value -- 書的信息
     */
    
    private Map<String,CartItem> map = new LinkedHashMap();
    private double price;  //購車中總的價格
    
    /**
     * 向購物車中添加 書本
     * @param book
     */
    public void add(Book book)
    {
        //根據(jù)書本的id   知道 購物車中是否已經(jīng)存入該商品
        CartItem cartItem= map.get(book.getId());
        if (cartItem!=null) {
            //已經(jīng)有該商品了 
            cartItem.setQuantity(cartItem.getQuantity()+1);
        }else{
            //該商品還沒有 需要進行創(chuàng)建
            cartItem=new CartItem();
            cartItem.setBook(book);
            cartItem.setQuantity(1);
            map.put(book.getId(), cartItem);
        }
    }
    
    /**
     * 獲取購物車
     * @return
     */
    public   Map<String, CartItem> getMap(){
        return map;
    }
    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }
    
    /**
     * 得到總價格
     * @return
     */
    public double getPrice(){
        double totalprice =0;
        for(Map.Entry<String, CartItem> me:map.entrySet()){
            CartItem cartItem=me.getValue();
            totalprice+=cartItem.getPrice();
        }
        return totalprice;
    }
    
    /**
     * 清空數(shù)據(jù)
     */
    public void clear(){
        getMap().clear();
    }
}
public class CartItem {
    private Book book;
    private int quantity;//購買的數(shù)量
    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 this.book.getPrice()*this.quantity;
    }
    public void setPrice(double price) {
        this.price = price;
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鬓催,一起剝皮案震驚了整個濱河市肺素,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌宇驾,老刑警劉巖倍靡,帶你破解...
    沈念sama閱讀 218,858評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異课舍,居然都是意外死亡塌西,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評論 3 395
  • 文/潘曉璐 我一進店門筝尾,熙熙樓的掌柜王于貴愁眉苦臉地迎上來捡需,“玉大人,你說我怎么就攤上這事筹淫≌净裕” “怎么了?”我有些...
    開封第一講書人閱讀 165,282評論 0 356
  • 文/不壞的土叔 我叫張陵损姜,是天一觀的道長饰剥。 經(jīng)常有香客問我,道長薛匪,這世上最難降的妖魔是什么捐川? 我笑而不...
    開封第一講書人閱讀 58,842評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮逸尖,結(jié)果婚禮上古沥,老公的妹妹穿的比我還像新娘瘸右。我一直安慰自己,他們只是感情好岩齿,可當(dāng)我...
    茶點故事閱讀 67,857評論 6 392
  • 文/花漫 我一把揭開白布太颤。 她就那樣靜靜地躺著,像睡著了一般盹沈。 火紅的嫁衣襯著肌膚如雪龄章。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,679評論 1 305
  • 那天乞封,我揣著相機與錄音做裙,去河邊找鬼。 笑死肃晚,一個胖子當(dāng)著我的面吹牛锚贱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播关串,決...
    沈念sama閱讀 40,406評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼拧廊,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了晋修?” 一聲冷哼從身側(cè)響起吧碾,我...
    開封第一講書人閱讀 39,311評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎墓卦,沒想到半個月后倦春,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡趴拧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年溅漾,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片著榴。...
    茶點故事閱讀 40,090評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡添履,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出脑又,到底是詐尸還是另有隱情暮胧,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評論 5 346
  • 正文 年R本政府宣布问麸,位于F島的核電站往衷,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏严卖。R本人自食惡果不足惜席舍,卻給世界環(huán)境...
    茶點故事閱讀 41,420評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望哮笆。 院中可真熱鬧来颤,春花似錦汰扭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至滑黔,卻和暖如春笆包,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背略荡。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評論 1 271
  • 我被黑心中介騙來泰國打工庵佣, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人撞芍。 一個月前我還...
    沈念sama閱讀 48,298評論 3 372
  • 正文 我出身青樓秧了,卻偏偏與公主長得像跨扮,于是被迫代替她去往敵國和親序无。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,033評論 2 355

推薦閱讀更多精彩內(nèi)容