zoukankan      html  css  js  c++  java
  • Java基础99 把商品加入购物车中及删除操作(Servlet技术,简单演示,只是把购物车添加到session中,不是以数据库的形式存储)

    1、建立购物车实体类  

    Cart 类 //实体类

     1 package com.shore.entity;
     2 
     3 import java.util.HashMap;
     4 import java.util.Map;
     5 
     6 /**
     7  * @author DSHORE/2019-5-16
     8  *
     9  */
    10 public class Cart {
    11     //Map集合中,可能有很多本书
    12     private Map<String, CartItem> items = new HashMap<String, CartItem>();//key:购物项对应的书的id  value:购物项
    13     private int num;//购物车中,书籍的数量
    14     private float price;//总价,付款时的金额
    15     
    16     public Map<String, CartItem> getItems() {
    17         return items;
    18     }
    19     
    20     public int getNum() {
    21         num = 0;
    22         for(Map.Entry<String, CartItem> me:items.entrySet()){
    23             num += me.getValue().getNum();
    24         }
    25         return num;
    26     }
    27     /*public void setNum(int num) {//不能设置书籍的数量
    28         this.num = num;
    29     }*/
    30     public float getPrice() {
    31         price = 0;
    32         for(Map.Entry<String, CartItem> me:items.entrySet()){
    33             price += me.getValue().getPrice();
    34         }
    35         return price;
    36     }
    37     /*public void setPrice(float price) {//不能设置价格
    38         this.price = price;
    39     }*/
    40 
    41     //把商品加入购物车
    42     public void addCart(Book book) {//同一本书,可购买了多本
    43         if(items.containsKey(book.getId())){
    44             //有这本书的id(当同一本书,我购买两本或更多本时,保持其他字段的属性不变,只增加数量)
    45             CartItem item = items.get(book.getId());
    46             item.setNum(item.getNum() + 1);//其他不改变,只增加数量
    47         }else{
    48             //没有这本书的id
    49             CartItem item = new CartItem();
    50             item.setBook(book);
    51             item.setNum(1);
    52             items.put(book.getId(), item);
    53         }
    54     }
    55 
    56     //删除购物车中的商品(同一种商品,有多个时,则是减少该商品的数量)
    57     public void deleteCartByBook(String bookId) {
    58         CartItem item = items.get(bookId);
    59         if (item.getNum() > 1) {//购物车中,同一商品,购买了多件,则每删除一次,该商品的数量就减一次(价格自动减少)
    60             item.setNum(item.getNum() - 1);//其他不改变,只减少数量
    61         }else {
    62             items.remove(bookId);
    63         }
    64     }
    65 }

    CartItem 类 //购物项类

     1 package com.shore.entity;
     2 
     3 /**
     4  * @author DSHORE/2019-5-16
     5  *
     6  */
     7 public class CartItem {//购物项
     8     private Book book;
     9     private int num;
    10     private float price;
    11     
    12     public Book getBook() {
    13         return book;
    14     }
    15     public void setBook(Book book) {
    16         this.book = book;
    17     }
    18     public int getNum() {
    19         return num;
    20     }
    21     public void setNum(int num) {
    22         this.num = num;
    23     }
    24     public float getPrice() {
    25         return num*book.getPrice();//计算出同一本书的总价(或同一类书)
    26     }
    27     /*public void setPrice(float price) {//不能设置价格
    28         this.price = price;
    29     }*/
    30 }

    2、建立Servlet类      

    ClientServlet 类

     1 package com.shore.web.controller.client;
     2 
     3 import java.io.IOException;
     4 import java.util.List;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 import javax.servlet.http.HttpSession;
    11 
    12 import com.shore.entity.Book;
    13 import com.shore.entity.Cart;
    14 import com.shore.entity.CartItem;
    15 import com.shore.service.BookService;
    16 import com.shore.service.impl.BookServiceImpl;
    17 
    18 /**
    19  * @author DSHORE/2019-5-12
    20  *
    21  */
    22 public class ClientServlet extends HttpServlet {
    23     private static final long serialVersionUID = 1L;//序列化
    24     BookService bService = new BookServiceImpl();
    25 
    26     public void doGet(HttpServletRequest request, HttpServletResponse response)
    27             throws ServletException, IOException {
    28         String operation = request.getParameter("operation");
    29         if ("addCartByBook".equals(operation)){
    30             addCartByBook(request,response);
    31         }else if("deleteCartByBook".equals(operation)){
    32             deleteCartByBook(request,response);
    33         }
    34     }
    35 
    36     //删除购物车中的商品(同一种商品,有多个时,则是减少该商品的数量)
    37     private void deleteCartByBook(HttpServletRequest request,
    38             HttpServletResponse response) throws ServletException, IOException {
    39         //获取数的id
    40         String bookId = request.getParameter("bookId");
    41         //从HttpSession中取出购物车
    42         HttpSession session = request.getSession();
    43         Cart cart = (Cart)session.getAttribute("cart");
    44         cart.deleteCartByBook(bookId); //直接调用 实体类Cart中的deleteCartByBook()方法
    45         /*//提示删除商品成功
    46         request.setAttribute("message","<script type='text/javascript'>alert('删除商品成功')</script>");*/
    47         request.getRequestDispatcher("/client/showCart.jsp").forward(request, response);
    48     }
    49 
    50     //购买书籍(把要购买的商品加入购物车)
    51     private void addCartByBook(HttpServletRequest request,
    52             HttpServletResponse response) throws ServletException, IOException {
    53         //获取数的id
    54         String bookId = request.getParameter("bookId");
    55         //获取要购买的书
    56         Book book = bService.findBookById(bookId);
    57         //从HttpSession中取出购物车
    58         HttpSession session = request.getSession();
    59         Cart cart = (Cart)session.getAttribute("cart");
    60         //没有:创建购物车,并放入到HttpSession中(购物车的car)
    61         if(cart == null){
    62             cart = new Cart();
    63             session.setAttribute("cart",cart);
    64         }
    65         //有:把书放到购物车中
    66         cart.addCart(book);//直接调用 实体类Cart中的addCart()方法
    67         //提示加入购物车成功
    68         request.setAttribute("message","<script type='text/javascript'>alert('加入购物车成功,请前去付款!')</script>");
    69         request.getRequestDispatcher("/index.jsp").forward(request, response);
    70     }
    71 
    72     public void doPost(HttpServletRequest request, HttpServletResponse response)
    73             throws ServletException, IOException {
    74         doGet(request, response);
    75     }
    76 }

    3、前端页面              

    showCart.jsp 购物车的页面(简单测试,页面随意搞搞的,还看得过去吧)

     1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
     2 <%@include file="/client/header.jsp"%>
     3 <style> 
     4     table tr th{ border:1px solid #C1C1C1; font-size: 16px;}
     5     table,table tr td { border:1px solid #C1C1C1; }
     6     table {  71%; min-height: 25px; line-height: 25px; border-collapse: collapse; padding:2px; margin:auto;text-align: center;}
     7 </style> 
     8 
     9 <h2 style="text-align: center;font-size: 20px">您购买的商品如下</h2>
    10    <c:if test="${empty sessionScope.cart.items}">
    11     <!-- 如果购物车为空(没商品),则显示这张图片,提示“购物车空空如也” -->
    12      <img height="432" width="720" src="${pageContext.request.contextPath}/images/0.jpg"/>
    13  </c:if>
    14  <c:if test="${!empty sessionScope.cart.items}">
    15      <table>
    16          <tr>
    17              <th>书名</th>
    18              <th>作者</th>
    19              <th>单价</th>
    20              <th>数量</th>
    21              <th>小计</th>
    22              <th>操作</th>
    23          </tr>
    24          <c:forEach items="${sessionScope.cart.items}" var="me">
    25              <tr>
    26               <td>${me.value.book.name}</td>
    27               <td>${me.value.book.author}</td>
    28               <td>${me.value.book.price}</td>
    29               <td>${me.value.num}</td>
    30               <td>${me.value.price}</td>
    31               <td>
    32                   <a href="${pageContext.request.contextPath}/ClientServlet?operation=deleteCartByBook&bookId=${me.value.book.id}">删除</a>
    33               </td>
    34           </tr>
    35          </c:forEach>
    36          <tr>
    37              <td colspan="6" align="right">
    38                  总数量:${sessionScope.cart.num}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    39                  应付款总金额:${sessionScope.cart.price}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    40                  <a href="${pageContext.request.contextPath}/ClientServlet?operation=genOrders" style="text-decoration: none;font-weight: bold;">付款购买</a>
    41                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    42              </td>
    43          </tr>
    44      </table>
    45  </c:if>
    46 ${message}

    效果图:

    把购物车中的商品购买支付、生成订单(Servlet技术,简单演示)

    原创作者:DSHORE

    作者主页:http://www.cnblogs.com/dshore123/

    原文出自:https://www.cnblogs.com/dshore123/p/10765588.html

    欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

  • 相关阅读:
    Caused by: java.lang.IllegalArgumentException: Not an managed type: class XXX
    SpringBoot配置文件详细解析
    解决eclipse环境下maven项目tomcat启动,未加载到项目的问题
    CSS+元素,鼠标事件触发鼠标模形变成手状的形状
    LeetCode-Wildcard Matching
    LeetCode-NQueensII
    LeetCode-Climbing Stairs
    LeetCode-Word Search
    LeetCode-Minimum Window Substring
    LeetCode-Largest Rectangle in Histogram
  • 原文地址:https://www.cnblogs.com/dshore123/p/10765588.html
Copyright © 2011-2022 走看看