模擬購(gòu)物車

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

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

/**
 * 模擬數(shù)據(jù)庫(kù)的數(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;
    }
}

書本的實(shí)體類

/**
 * 書的實(shí)體類
 */
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;
    }
}

接下來(lái)是 Dao

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

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

/**
 * 書本業(yè)務(wù)的邏輯   用于和 dao層 和 view進(jìn)行交互數(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);
    }
    
    /**
     * 清空購(gòu)物車
     * @param cart
     * @throws CartNotFoundException 
     */
    public void clear(Cart cart) throws CartNotFoundException{
        if (cart ==null) {
            throw new CartNotFoundException();
        }
        cart.clear();
    }
    
    /**
     * 刪除購(gòu)物車中的商品
     * @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ù)量進(jìn)行改變
     * @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

 /**
  * 書本的列表頁(yè)
  */
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>書籍編號(hào)</td>
            <td>書名</td>
            <td>作者</td>
            <td>售價(jià)</td>
            <td>描述</td>
            <td>操作</td>
        </tr>
        
        <%-- Set<Map.Entry<String,Book>>  每次循環(huán)出來(lái)的就是這個(gè)--%> 
        <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}">購(gòu)買</a>
            </td>
        </tr>
        </c:forEach>
         
    </table>
</body>
</html>

購(gòu)買書本后的servlet

/**
 *  點(diǎn)擊購(gòu)買按鈕調(diào)到此界面進(jìn)行處理
 */
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);
        }
         //將商品加入購(gòu)物車中 
         BusinessService businessService=new BusinessService();
         businessService.buybook(bookid, cart);
         //展示購(gòu)買過(guò)的商品
         request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    }

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

}

展示購(gòu)買的商品的 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>購(gòu)買過(guò)的商品</title>
<script type="text/javascript">
    /*  清空購(gòu)物車  */
    function clearcart() {
        var isClear=window.confirm("您確定要清空購(gòu)物車嗎??");
        if(isClear){
            window.location.href="${pageContext.request.contextPath}/ClearCartServlet";
        }
    }
    
    /*更新 顯示的數(shù)據(jù)*/
    function updateCart(input, id){
        // input 輸入的內(nèi)容   id 是更新的是哪個(gè) 商品
        var quantity=input.value;
        var b = window.confirm("請(qǐng)確認(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>購(gòu)物車列表</h2>
    <br/><br/>
    <!-- 當(dāng)購(gòu)物車不是空 -->
    <c:if test="${!empty(cart.map)}">
        <table border="1" width="80%">
            <tr>
                <td>書名</td>
                <td>作者</td>
                <td>單價(jià)</td>
                <td>數(shù)量</td>
                <td>小計(jì)</td>
                <td>操作</td> 
            </tr>
            
            <!-- Set<Map.Entry<String,CarItem>>  每次循環(huán)出來(lái)的就是這個(gè)  -->
           <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()">清空購(gòu)物車</a>
            </td>
            <td colspan="2">合計(jì)</td>
            <td colspan="2">${cart.price}</td>
        </tr>
           
         </table>
    </c:if> 
    
    <c:if test="${empty(cart.map)}">
          對(duì)不起,您還沒有購(gòu)買任何商品
    </c:if>
    
</body>
</html>

清空購(gòu)物車的 servlet

/**
 * 清空購(gòu)物車哦
 */
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","對(duì)不起,您還沒有購(gòu)買任何商品!!!");
             request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

刪除 商品的 sevlet

/**
 *  刪除 購(gòu)物列表中的數(shù)據(jù)
 */
public class DeleteServlet extends HttpServlet {
 
     
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String bookid=request.getParameter("bookid");
        //將次數(shù)的id從購(gòu)物車進(jìn)行刪除
        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","對(duì)不起,您還沒有購(gòu)買任何商品!!!");
             request.getRequestDispatcher("/message.jsp").forward(request, response); 
        }
    }

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

}

當(dāng)在購(gòu)買過(guò)的商品中進(jìn)行修改商品的數(shù)量的時(shí)候

/**
 * 當(dāng)修改購(gòu)買商品的數(shù)量 進(jìn)行操作的 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","對(duì)不起,您還沒有購(gòu)買任何商品!!!");
             request.getRequestDispatcher("/message.jsp").forward(request, response); 
        }
         
         
    }

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

購(gòu)物車的實(shí)體

/**
 * 購(gòu)物車
 */
public class Cart {
    
    /**
     * 用于存儲(chǔ) 購(gòu)車車中的信息   key--- id   value -- 書的信息
     */
    
    private Map<String,CartItem> map = new LinkedHashMap();
    private double price;  //購(gòu)車中總的價(jià)格
    
    /**
     * 向購(gòu)物車中添加 書本
     * @param book
     */
    public void add(Book book)
    {
        //根據(jù)書本的id   知道 購(gòu)物車中是否已經(jīng)存入該商品
        CartItem cartItem= map.get(book.getId());
        if (cartItem!=null) {
            //已經(jīng)有該商品了 
            cartItem.setQuantity(cartItem.getQuantity()+1);
        }else{
            //該商品還沒有 需要進(jìn)行創(chuàng)建
            cartItem=new CartItem();
            cartItem.setBook(book);
            cartItem.setQuantity(1);
            map.put(book.getId(), cartItem);
        }
    }
    
    /**
     * 獲取購(gòu)物車
     * @return
     */
    public   Map<String, CartItem> getMap(){
        return map;
    }
    public void setMap(Map<String, CartItem> map) {
        this.map = map;
    }
    
    /**
     * 得到總價(jià)格
     * @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;//購(gòu)買的數(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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容