先设置一个product类,用来存储和获取数据,使用LIst集合存储所有商品即(ProductDao类),在ShowProductServlet类查看商品信息,然后将数据提交到AddCarServlet类来处理数据,最后在ShowCarServlet类查看购物车并显示数量和价格。

程序运行如下图所示:

ShowProductServlet类显示效果

ShowCarServlet类查看购物车

源代码如下:

Product

package star.july.buycar;public class Product {private int id;private String name;private int price;public void setPrice(int price) {this.price = price;}private String descr;private int num =1;  //默认值public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescr() {return descr;}public void setDescr(String descr) {this.descr = descr;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public int getPrice(){return price;}public Product(int id, String name, int price, String descr) {super();this.id = id;this.name = name;this.price = price;this.descr = descr;}public Product() {super();}}

ProductDao:

package star.july.buycar;import java.util.ArrayList;
import java.util.List;//商品dao类
public class ProductDao {//存储所有的商品的集合public static List<Product> data = new ArrayList<Product>();static{data.add(new Product(1,"三星",4500,"Android机皇"));data.add(new Product(2,"苹果",5800,"ISO系统,流畅爽快"));data.add(new Product(3,"小米",1999,"为发烧而生"));data.add(new Product(4,"华为",2888,"强大的研发实力"));data.add(new Product(5,"一加",1999,"超高的性价比"));}//返回所有的商品数据public List<Product> findAll(){return data;}//根据id查找商品public Product findById(int id){for(Product p:data){if(p.getId() == id){return p;}}return null;}
}

ShowProductServlet:

package star.july.buycar;import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class ShowProductServlet extends HttpServlet {ProductDao dao = new ProductDao();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List<Product> product = dao.findAll();        //返回Product对象 //显示中文response.setContentType("text/html;charset=utf-8");//显示商品列表String html ="";html += "<html><body>";html +="<table border='1' width = 500px>";html += "<tr><th>编号</th><th>品牌</th><th>价格</th><th>描述</th><th>购买</th>";for(Product p: product){html += "<tr><td>"+p.getId()+"</td><td>"+p.getName()+"</td>" +"<td>"+p.getPrice()+"</td><td>"+p.getDescr()+"</td>" +//getContextPath:获取父目录。 在超链接中传递商品的id,用以添加商品数量"<td><a href='"+request.getContextPath()+"/AddCarServlet?id="+p.getId()+"'>购买</a></td>";   } html += "</table>";html += "</body></html>";response.getWriter().write(html);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {}}

AddCarServlet:

package star.july.buycar;import java.io.IOException;
import java.util.HashMap;
import java.util.Map;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class AddCarServlet extends HttpServlet {ProductDao dao = new ProductDao();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//获得IDString id = request.getParameter("id");//查找商品Product product = dao.findById(Integer.parseInt(id)); //获取sessionHttpSession session = request.getSession();//设计一个集合用以存储购物车中的所有商品数据//使用session.getAttribute()是为了判断第一个商品Map<Integer,Product> car = (Map<Integer, Product>) session.getAttribute("car");//如果是第一个商品,就进行初始化if(car == null ){car = new HashMap<Integer,Product>();}if(car != null && car.containsKey(Integer.parseInt(id))){  //判断是否是集合里的key的值 Product p = car.get(Integer.parseInt(id));             //返回key(id)对应的值p.setNum(p.getNum()+1);                                   //商品数量+1}else{//没有买过,需要重新加入购物车car.put(product.getId(), product);}//将car的值赋值给属性car,后者给前者session.setAttribute("car", car);//回显response.setContentType("text/html;charset=utf-8");response.getWriter().write(product.getName()+"已成功加入购物车! <a href = '"+request.getContextPath()+"/ShowCarServlet'>查看购物车</a>");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

ShowCarServlet:

package star.july.buycar;import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;public class ShowCarServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//从HttpSession中取出数据HttpSession session = request.getSession();Map<Integer,Product> car =(Map<Integer,Product>)session.getAttribute("car");//显示中文response.setContentType("text/html;charset=utf-8");String html ="";html += "<html><body>";html +="<table border='1' width = 500px>";html += "<tr><th>编号</th><th>品牌</th><th>价格</th><th>数量</th><th>描述</th><th>小计</th>";double totalProduct = 0;        //商品的总价for(Entry<Integer,Product> entry : car.entrySet()){Product p = entry.getValue(); html += "<tr><td>"+p.getId()+"</td><td>"+p.getName()+"</td>" +"<td>"+p.getPrice()+"元</td><td>"+p.getNum()+"</td><td>"+p.getDescr()+"" +"</td><td>"+p.getPrice()*p.getNum()+"元</td>";totalProduct += p.getPrice()*p.getNum();} html += "<tr><td colspan ='6' align='right'>合计:"+totalProduct+"元</td></tr>";html += "</table>";html += "<p><a href='"+request.getContextPath()+"/ShowProductServlet'>继续购物</a>";html += "</body></html>";response.getWriter().write(html);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}

面向对象中的session版的购物车相关推荐

  1. 购物车(session版)

    目录: 一:详解购物车 1.1:购物车页面数据绑定 1.2:购物车功能(添加,删除,结算) 二:项目美化小知识 一:详解购物车 注:session版购物车它是在eclipse项目中利用Java Res ...

  2. 你注意到 .Net Framework 和 .Net Core 中使用 Session 的区别了吗?

    起因 在测试一个例子时发现的问题,这个示例实现的功能是刷新页面也能保持表格锁定列的状态,先看下页面的完成效果: 测试中发现,几乎相同的代码: 在 FineUIMvc(Net Framework)下没有 ...

  3. Tomcat 集群中 实现session 共享的三种方法

    前两种均需要使用 memcached 或 redis 存储 session ,最后一种使用 terracotta 服务器共享.  建议使用 redis ,不仅仅因为它可以将缓存的内容持久化,还因为它支 ...

  4. hibernate中SessionFactory,Session的理解?

    Session接口         Session接口对于Hibernate   开发人员来说是一个最重要的接口.然而在Hibernate中,实例化的Session是一个轻量级的类,创建和销毁它都不会 ...

  5. 你注意到 .Net Framework 和 .Net Core 中使用 Session 的区别了吗?

    在测试一个例子时发现的问题,这个示例实现的功能是刷新页面也能保持表格锁定列的状态,先看下页面的完成效果: 测试中发现,几乎相同的代码: 在 FineUIMvc(Net Framework)下没有问题: ...

  6. 案例:实现在购物车中添加商品和删除购物车中指定商品的功能

    一.向购物车中添加商品 1.1.创建AddCartServlet public class AddCartServlet extends HttpServlet {public void doGet( ...

  7. [Object]面向对象编程(高程版)(二)原型模式

    [Object]面向对象编程(高程版)(二)原型模式 博客分类: Web前端-JS语言核心 作者:zccst 三.原型模式 每个函数都有一个prototype(原型)属性,这个属性是一个指针,指向一个 ...

  8. 较为周全的Asp.net提交验证方案(Session版)

    此前我介绍了使用数据库实现的提交验证方案,一些朋友怀疑其效率不佳,认为Session是更好的方案. 的确使用Session也不会消耗太多内存,而且如今内存白菜价,最不济就随手买个2G的插上也就够了,所 ...

  9. 浅谈Session并且实现购物车

    Session Session(会话机制),会话机制其实就是一个信息共享域,可以保留客户端每次发送请求的信息 Session和Attribute 由于Http协议是无状态的,只会保留当前请求,也就是再 ...

最新文章

  1. Class Activation Mapping (CNN可视化) Python示例
  2. mysql当前时间加一天_MySQL 的加锁处理,你都了解的一清二楚了吗?
  3. 金融数据信噪比的影响力又一力证
  4. OpenGL实现Cubic Environment Map立方环境图实例
  5. php安装dat,PHP Parsing a .dat file
  6. ad file type not recognised_Java实用工具类:File工具类方法学习,可创建目录及文件...
  7. 产业数字化升级进入深化期,腾讯智慧出行释放“数字底座”核心能力
  8. Linux五种清理系统垃圾的方式
  9. zabbixdocker里的mysql_基于Docker安装与部署Zabbix
  10. Linux C 错误 invalid application of 'sizeof' to incomplete type 解决方案
  11. linux内核驱动之 驱动程序的角色
  12. SQLAlchemy schema.MetaData
  13. vs2017 Visual Studio 离线安装方法
  14. es6 对象中是否有键值_JS获取对象键值对中key值的方法
  15. 运营主管的OKR案例
  16. 【可视化分析】雷达图
  17. windows系统镜像修复计算机,电脑映像损坏怎么修复_windows提示损坏的映像怎么处理...
  18. 那些在一个公司死磕了5-10年的人,最后都怎么样了?那些在一个公司死磕了5-10年的人,最后都怎么样了?...
  19. 大学四年是这么度过的——大学四年总结
  20. linux系统查看系统配置

热门文章

  1. 跨链(5)“蚂蚁区块链”之跨链数据连接服务
  2. 区块链BaaS云服务(16)天德链TDBC“金丝猴链”
  3. 基于区块链的健康链系统设计与实现(3)系统设计
  4. 创新实训个人记录:metric k-center
  5. BUU--[MRCTF2020]PixelShooter
  6. 各个级别镜像之间的跳转模型
  7. 2022-03-17
  8. 无法上外网又需要同步Gradle
  9. redis的五种数据类型及常见操作
  10. Intel VT学习笔记(四)—— VMCS(下)