• estore商城案例(四、五)------添加购物车&购物车显示/生成订单&在线支付


    一、添加购物车

    1、获得商品id提交到servlet程序

    2、根据id获取product对象

    3、判断seesion中是否有存在购物车session。没有的话表示  添加的第一件商品  需要先创建session;有的话直接在session里添加获得的produce(添加product 要先判断session中是否存在对应的商品,存在话直接修改商品数量,没有的话新添加这个商品)。

    servlet程序代码:

     1 public void doGet(HttpServletRequest request, HttpServletResponse response)
     2             throws ServletException, IOException {
     3         //获取传过来的id根据id或product对象,
     4         String id=request.getParameter("id");
     5         if(!"".equals(id)&&id!=null)
     6         {
     7             Product p=new Product();
     8             p.setId(id);
     9             ProductService ps=new ProductServiceImpl();
    10             p=ps.getProduct(p);
    11             if(p!=null)
    12             {
    13                 //判断seesion中是否有存在购物车session
    14                 Map<Product,Integer> cart=(Map<Product, Integer>) request.getSession().getAttribute("cart");
    15                 if(cart==null){
    16                     //没有的话表示  添加的第一件商品  需要先创建session
    17                     cart=new HashMap<Product, Integer>();
    18                 }
    19               
    20                     //有的话直接在session里添加获得的produce
    21                     //添加product 判断session中是否存在对应的商品  存在话直接修改商品数量,没有的话新添加这个商品
    22                     if(cart.containsKey(p))
    23                     {
    24                         //存在话直接修改商品数量
    25                         int i=cart.get(p)+1;
    26                         cart.put(p, i);
    27                     }
    28                     else
    29                     {
    30                         //没有的话新添加这个商品,并附加上商品的所有信息
    31                         cart.put(p, 1);
    32                     }
    33                     response.setContentType("text/html;charset=utf-8");
    34                 request.getSession().setAttribute("cart", cart);
    35                 response.getWriter().print("添加到 购物车成功 . <a href='"+request.getContextPath()+"/listproducts'>继续购物</a><br/><a href='"+request.getContextPath()+"/cart.jsp'>查看购物车</a>");
    36                 return;
    37             }
    38 
    39         }
    40         request.getRequestDispatcher("/listproducts").forward(request, response);
    41     }
    View Code

    service层和dao层在estore商城案例(二)------登录&添加商品&商品列表(下)中。

    二、购物车显示

    直接在jsp中遍历购物车session:

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     3 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     4 <html>
     5   <head>
     6     <title>My JSP 'cart.jsp' starting page</title>
     7   </head>
     8   <body>
     9     <c:if test="${empty cart }">
    10         你还木有购买过任何商品
    11     </c:if>
    12     <c:if test="${not empty cart }">
    13         <h3>您购买的商品有 :</h3>
    14         <table border="1" width="100%">
    15             <tr>
    16                 <td>商品编号</td>
    17                 <td>商品名称</td>
    18                 <td>商品价格</td>
    19                 <td>购买数量</td>
    20                 <td>库存情况</td>
    21             </tr>
    22             <!--  Ma<> -->
    23             <c:forEach items="${cart }" var="entry">
    24                 <tr>
    25                     <td>${entry.key.id }</td>
    26                     <td>${entry.key.name }</td>
    27                     <td>${entry.key.price }</td>
    28                     <td>${entry.value }</td>
    29                     <td>
    30                         <c:if test="${entry.key.pnum>=entry.value }">
    31                             <font color="red">现货充足</font>
    32                         </c:if>
    33                         <c:if test="${entry.key.pnum<entry.value }">
    34                             <font color="gray">库存紧张</font>
    35                         </c:if>
    36                     </td>
    37                     <c:set var="totalprice" value="${totalprice+ entry.key.price*entry.value }"></c:set>
    38                 </tr>
    39             </c:forEach>
    40             <tr>
    41                 <td colspan="5" align="right" style="color: red">
    42                     商品总价: ${totalprice }
    43                 </td>
    44             </tr>
    45         </table>
    46         <div align="right">
    47             <img src="/myestore/img/gotoorder.bmp" style="cursor: pointer;" onclick="location.href='${pageContext.request.contextPath}/add_order.jsp';">
    48         </div>
    49     </c:if>
    50 </body>
    51 </html>
    View Code

    三、订单生成

    1、先生成订单页面、然后封装订单信息计较到servlet。

    2、订单信息封装到订单(order)实体中,获得用户session中的id,赋值给order实体中。

    3、维护第三张出货表(orderitem)中的数据;从购物车cart中获取详细的信息填入orderitem实体中;

    4、执行生成订单、创建商品出货表(orderitem)、修改商品表中相应商品的数量的操作。这里注意,这三个操作要么同时成功,要么同时失败,所以要在事务中执行。

    订单页面:

     1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     3 
     4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     5 <html>
     6   <head>
     7    
     8     <title>My JSP 'add_order.jsp.jsp' starting page</title>
     9    
    10   </head>
    11   
    12   <body>
    13     <h1>生成订单</h1>
    14     <form action="${pageContext.request.contextPath }/generateorder" method="post">
    15         <table>
    16             <tr>
    17                 <td>收货人信息 </td>
    18                 <td>
    19                     <textarea cols="80" rows="5" name="receiverinfo"></textarea>
    20                 </td>
    21             </tr>
    22             <tr>
    23                 <td>付款方式 </td>
    24                 <td style="color: red">
    25                     <input type="radio" name="paymethod" value="yibaozhifu">易宝支付
    26                     <input type="radio" name="paymethod" value="alipay">支付包
    27                     <input type="radio" name="paymethod" value="caifutong">财付通
    28                 </td>
    29             </tr>
    30         </table>
    31         <h3>购买商品详情</h3>
    32         <table border="1" width="100%">
    33             
    34             <tr>
    35                 <td>商品编号</td>
    36                 <td>商品名称</td>
    37                 <td>商品价格</td>
    38                 <td>购买数量</td>
    39                 <td>库存情况</td>
    40             </tr>
    41             <!--  Ma<> -->
    42             <c:forEach items="${cart }" var="entry">
    43                 <tr>
    44                     <td>${entry.key.id }</td>
    45                     <td>${entry.key.name }</td>
    46                     <td>${entry.key.price }</td>
    47                     <td>${entry.value }</td>
    48                     <td>
    49                         <c:if test="${entry.key.pnum>=entry.value }">
    50                             <font color="red">现货充足</font>
    51                         </c:if>
    52                         <c:if test="${entry.key.pnum<entry.value }">
    53                             <font color="gray">库存紧张</font>
    54                         </c:if>
    55                     </td>
    56                     <c:set var="totalprice" value="${totalprice+ entry.key.price*entry.value }"></c:set>
    57                 </tr>
    58             </c:forEach>
    59             <tr>
    60                 <td colspan="5" align="right" style="color: red">
    61                     商品总价: ${totalprice }
    62                     <input type="hidden" name="money" value="${totalprice }">
    63                 </td>
    64             </tr>
    65         </table>
    66         <input type="submit" value="生成订单">
    67     </form>
    68 </body>
    69 </html>
    View Code

    servlet程序:

     1 public void doGet(HttpServletRequest request, HttpServletResponse response)
     2             throws ServletException, IOException {
     3         //订单信息封装到order实体中
     4         Order order=new Order();
     5         try {
     6             BeanUtils.populate(order, request.getParameterMap());
     7             //获得session中用户的id,传给赋值给order实体中
     8             User user = (User) request.getSession().getAttribute("existUser");
     9             order.setUser_id(user.getId());
    10             //维护第三张表orderitem中的数据,从cart中获取详细的信息
    11             Map<Product,Integer>map=(Map<Product, Integer>) request.getSession().getAttribute("cart");
    12             List<OrderItem> orderitem=new ArrayList<OrderItem>();
    13             for(Product p:map.keySet())
    14             {
    15                 OrderItem ord=new OrderItem();
    16                 ord.setProduct_id(p.getId());
    17                 ord.setBuynum(map.get(p));
    18                 //ord.id???
    19                 orderitem.add(ord);
    20             }
    21             order.setList(orderitem);
    22             //执行生成订单创建商品出货表(orderitem)修改商品 表中相应商品的数量
    23             OrderService os=new OrderServiceImpl();
    24             int b=os.insert(order);
    25             response.setContentType("text/html;charset=utf-8");
    26             request.getSession().removeAttribute("cart");
    27             if(b==OrderServiceImpl.SUCCESS)
    28             {
    29             //订单生成成功
    30             //清理购物车
    31             //response.getWriter().print("订单生成成功!!!!!<a href='"+request.getContextPath()+"/index.jsp'>返回</a>");
    32             //跳转到在线支付页面
    33                 Order orders=OrderServiceImpl.ORDERS;
    34                 request.getSession().setAttribute("orders", orders);
    35                 request.getRequestDispatcher("/gopay.jsp").forward(request, response);
    36             //完成支付后,修改订单状态
    37                 //由支付公司回传数据给callbackpay 自己写的servlet程序 判断回传有效性后,判断回传结果......
    38             return;
    39             }
    40             if(b==OrderServiceImpl.NOTENOUGH){
    41                 response.getWriter().print("库存不足啦!!!!!<a href='"+request.getContextPath()+"/index.jsp'>返回</a>");
    42             return;
    43             }
    44             if(b==OrderServiceImpl.FAIL){
    45                 response.getWriter().print("订单生成失败!!!!!<a href='"+request.getContextPath()+"/index.jsp'>返回</a>");
    46                 return;
    47             }
    48         } catch (Exception e) {
    49 
    50             e.printStackTrace();
    51             throw new MyRuntimeException(e);
    52         } 
    53 
    54     }
    View Code

    orderserviceImpl:(接口orderservice没写)

     1 public class OrderServiceImpl implements OrderService {
     2     public static int SUCCESS=1;
     3     public static int FAIL=0;
     4     public static int NOTENOUGH=-1;
     5     public static Order ORDERS=null;
     6 private OrderItemDao oidao=DaoFactory.getInstance().createDao(OrderItemDao.class);
     7 private OrderDao odao=DaoFactory.getInstance().createDao(OrderDao.class);
     8 private ProductDao pdao=DaoFactory.getInstance().createDao(ProductDao.class);
     9     @Override
    10     public int insert(Order order) {
    11         //创建事务 处理 添加订单order,添加订单详情表orderitem,修改product库存
    12         // ThreadLocal 类 , 内部维护了 一个map , key就是当前线程, value 就是你存的对象
    13                 // 将一个 connection 存入到 这个 Threalocal的 实例中, 那么这个connecttion 也就
    14                 // 绑定 与 当前线程 上了 
    15         try{
    16         utils.TransactionUtils.startTransaction();
    17         //1,生成订单插入order表
    18         String orderId="order"+utils.UUIDtoHashCode.getUUIDHsahCode();
    19         order.setId(orderId);
    20         odao.insert(TransactionUtils.getConnection(),order);
    21         //oreritem表
    22         List<OrderItem>orderitem=new ArrayList<OrderItem>();
    23         orderitem=order.getList();
    24         for (OrderItem odi : orderitem) {
    25             odi.setOrder_id(orderId);
    26             oidao.insert(TransactionUtils.getConnection(),odi);
    27             pdao.update(TransactionUtils.getConnection(),odi);
    28         }
    29         ORDERS=order;
    30         TransactionUtils.commit();
    31         return SUCCESS;
    32         }
    33         catch (Exception e) {
    34             // TODO: handle exception
    35             // 回滚事务 
    36             TransactionUtils.roolback(); 
    37             if("not enough".equalsIgnoreCase(e.getMessage()))
    38             {
    39                 
    40                 return NOTENOUGH;
    41             }
    42         }
    43         return FAIL;
    44     }
    View Code

    事务工具包:

     1 public class TransactionUtils {
     2     //创建线程变量为Connection的threadlocal(tl)
     3     private static ThreadLocal<Connection> tl=new ThreadLocal<Connection>();
     4     private static Connection con=JdbcUtils.getConnection();
     5     //给这个tl初始化 connection值
     6     public static Connection getConnection()
     7     {
     8         if(tl.get()==null)
     9         {
    10         tl.set(con);
    11         }
    12         return tl.get();        
    13     }
    14     //开始transaction
    15     public static void startTransaction()
    16     {
    17         Connection conn=tl.get();
    18         if(conn==null)
    19             conn=getConnection();
    20         try {
    21             
    22             conn.setAutoCommit(false);
    23         } catch (SQLException e) {
    24             
    25             e.printStackTrace();
    26             throw new MyRuntimeException(e);
    27         }
    28     }
    29     //commit
    30     public static void commit()
    31     {
    32         Connection conn=tl.get();
    33         if(conn==null)
    34             conn=getConnection();
    35         try {
    36             conn.commit();
    37         } catch (SQLException e) {
    38             
    39             e.printStackTrace();
    40             throw new MyRuntimeException(e);
    41         }
    42     }
    43     //rollback
    44     public static void roolback()
    45     {
    46         Connection conn=tl.get();
    47         if(conn==null)
    48             conn=getConnection();
    49         try {
    50             
    51             conn.rollback();
    52         } catch (SQLException e) {
    53             
    54             e.printStackTrace();
    55             throw new MyRuntimeException(e);
    56         }
    57     }
    58 
    59 }
    View Code

    四、在线支付

    这里使用的是易宝支付的接口,不同第三方支付都会提供差不多的支付pai这里我就直接附上我的整个项目源码了:

    http://pan.baidu.com/s/1hq7nDe0

  • 相关阅读:
    Spark学习笔记1
    Scala学习笔记
    Scala实现网站流量实时分析
    使用Docker搭建Spark集群(用于实现网站流量实时分析模块)
    使用Docker搭建Hadoop集群(伪分布式与完全分布式)
    Docker配置阿里云镜像源
    从centos7镜像到搭建kubernetes集群(kubeadm方式安装)
    来做一个简单的成绩查询!(输入输出)
    String类的知识点(不断更新)
    人机猜拳游戏Java
  • 原文地址:https://www.cnblogs.com/cmds/p/3920572.html
Copyright © 2020-2023  润新知