初学者 模拟购物车(包含添加商品和删除商品功能)

来源:互联网 发布:复旦投毒案的思考知乎 编辑:程序博客网 时间:2024/05/29 21:36

购物车界面与功能实现分析图:




购物车对象:

package cn.itsource._01_buycart.domain;import java.util.ArrayList;import java.util.Iterator;import java.util.List;/** *  购物车对象 * */public class ShoppingCart {//表示购物车对象中的所有商品private List<CartItem> items = new ArrayList<>();public List<CartItem> getItems() {return items;}public void setItems(List<CartItem> items) {this.items = items;}/** *  计算购物车中商品总价 * */public Double getTotalPrice(){Double totalPrice = 0D;for (CartItem item : items) {totalPrice += item.getPrice()*item.getNum(); }return totalPrice;}/** *  设计一个向购物车中添加商品的方法 * */public void save(CartItem newItem){/** *  遍历所有的商品,如果商品相同,就将数量进行相加 *  如果全部不同,则需要把商品单独添加到购物车 * */for (CartItem item : items) {//比较idif(newItem.getId().equals(item.getId())){//修改item的数量  .item是购物车原有的数据item.setNum(item.getNum() +newItem.getNum());return; //不终止代码执行,则会执行后面的代码。}}//如果全部不同,则需要把商品单独添加到购物车items.add(newItem);}/** *  从购物车中删除一个商品 * */public void delete(String id){/** *  在使用遍历时,如果对遍历的这个集合进行修改或者删除的话。容易出现线程并发安全问题(线程并发修改异常) * *//*for (CartItem item : items) {if(id.equals(item.getId())){items.remove(item);break;}}*//** *  从集合中删除一个商品,需要使用迭代器。使用 Iterator对象.remove()方法删除 * */ Iterator<CartItem> it = items.iterator();//拿到迭代器 while(it.hasNext()){   //hasNext():是否存在下一个对象元素 CartItem item =  it.next();//拿到购物车中所有商品 //判断。如果商品id和传过来的id一样,则删除 if(id.equals(item.getId())){ it.remove(); break; } }}@Overridepublic String toString() {return "ShoppingCart [items=" + items + "]";}}

购物车中的商品项:

package cn.itsource._01_buycart.domain;/** *  该类表示购物车中的一个商品项 * */public class CartItem {//商品编号private String id;//商品名称private String name;//商品价格private Double price;//商品数量private Integer num;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;}public Integer getNum() {return num;}public void setNum(Integer num) {this.num = num;}@Overridepublic String toString() {return "CartItem [id=" + id + ", name=" + name + ", price=" + price + ", num=" + num + "]";}}

实现购物车的servlet:

package cn.itsource._01_buycart.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import cn.itsource._01_buycart.domain.CartItem;import cn.itsource._01_buycart.domain.ShoppingCart;/** *  购物车实现servlet * */@WebServlet("/shoppingCart")public class ShoopingCartServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {req.setCharacterEncoding("UTF-8");String cmd = req.getParameter("cmd");/** *  传入一个cmd 用来做删除 * */if("delete".equals(cmd)){//1.拿到参数 idString id = req.getParameter("id");//2.从session中拿到购物车HttpSession session = req.getSession();ShoppingCart cart = (ShoppingCart)session.getAttribute("SHOPPING_IN_CART");//3.从购物车中删除相应的商品cart.delete(id);//4.跳转到展示页面resp.sendRedirect("/buycart/buycart.jsp");}else{/** *  实现商品添加功能 *  1.拿到参数,封装CartItem(商品项)对象 *  2.从session中拿到购物车 *  如果session中没有购物车,创建购物车并放到session中 *  3.将CartItem(商品项)对象放到购物车 *  4.跳转到展示页面 * */String id = req.getParameter("id");String num = req.getParameter("num");//为了封装对象,所以需要创建商品对象 。以下代码完成了第一步CartItem item = new CartItem();item.setId(id);//因为都要设置id就不需要每个都设置,直接在外面设置。item.setNum(Integer.parseInt(num));if("1".equals(id)){item.setName("苹果电脑");item.setPrice(10000D);}else if("2".equals(id)){item.setName("苹果手机");item.setPrice(7000D);}else if("3".equals(id)){item.setName("苹果手表");item.setPrice(10000D);}//2.从session中拿到购物车   如果session中没有购物车,创建购物车并放到session中HttpSession session = req.getSession();ShoppingCart cart = (ShoppingCart)session.getAttribute("SHOPPING_IN_CART");if(cart == null){  //判断购物车为空cart = new ShoppingCart(); //创建一个购物车session.setAttribute("SHOPPING_IN_CART", cart);//将购物车放到session中}//3.将CartItem(商品项)对象放到购物车. 调用save()方法即可cart.save(item);//4.跳转到展示页面resp.sendRedirect("/buycart/buycart.jsp");}}}

(表单样式显示购物车)buycart.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>Insert title here</title><style type="text/css">table{border-collapse: collapse;width: 500px;text-align: center;}table th,table td{border: 1px solid black;}</style></head><body>
<%@ 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>Insert title here</title><style type="text/css">table{border-collapse: collapse;width: 500px;text-align: center;}table th,table td{border: 1px solid black;}</style></head><body><%--展示购物车    因为购物车放到session中的。  JSP九大内置对象就有session --%><a href="/buycart/edit.jsp">买</a><table><tr><th>商品编号</th><th>商品名称</th><th>商品价格</th><th>商品数量</th><th>操作</th></tr><c:if test="${not empty SHOPPING_IN_CART.items}"><%--  使用遍历的方式,获得所有商品的信息,并使用表格的方式显示出来 --%><c:forEach items="${SHOPPING_IN_CART.items}" var="item"><tr><td>${item.id}</td><td>${item.name}</td><td>${item.price}</td><td>${item.num}</td><td><a href="/shoppingCart?cmd=delete&id=${item.id}">删除</a></td></tr></c:forEach><tr><td colspan="5">总价格:${SHOPPING_IN_CART.totalPrice}</td></tr></c:if><c:if test="${empty SHOPPING_IN_CART.items}"><td colspan="5">您的购物车中没有商品,请选购。</td></c:if></table></body></html>

<%--展示购物车 因为购物车放到session中的。 JSP九大内置对象就有session --%><a href="/buycart/edit.jsp">买</a><table><tr><th>商品编号</th><th>商品名称</th><th>商品价格</th><th>商品数量</th><th>操作</th></tr><c:if test="${not empty SHOPPING_IN_CART.items}"><%-- 使用遍历的方式,获得所有商品的信息,并使用表格的方式显示出来 --%><c:forEach items="${SHOPPING_IN_CART.items}" var="item"><tr><td>${item.id}</td><td>${item.name}</td><td>${item.price}</td><td>${item.num}</td><td><a href="/shoppingCart?cmd=delete&id=${item.id}">删除</a></td></tr></c:forEach><tr><td colspan="5">总价格:${SHOPPING_IN_CART.totalPrice}</td></tr></c:if><c:if test="${empty SHOPPING_IN_CART.items}"><td colspan="5">您的购物车中没有商品,请选购。</td></c:if></table></body></html>

展示页面 edit.jsp:


阅读全文
0 0
原创粉丝点击