JavaWeb-仿小米商场(7) 提交订单

JavaWeb-仿小米商场(7) 提交订单,第1张

JavaWeb-仿小米商场(7) 提交订单 1 功能描述

接上篇 JavaWeb - 仿小米商城(5):商品添加到购物车 本篇博客将分析和实现小米商城通过购物车生成订单:通过

订单界面,订单创建成功,显示订单预览界面,在本页面可以显示和添加收货地址

支付提示界面:当点击提交页面,此时将订单数据存储到数据表中

支付宝支付:一般开发中使用沙箱做模拟支付

支付成功可以通过我的订单查看订单

订单详情,通过点击订单详情,跳转到订单详情页面

2 提交订单功能分析 2.1 功能逻辑抽象

商品购物车点击生成订单时,先判断用户是否登录,如果用户没有登录,则需要用户先完成登录 ,获取到用户对象,然后从购物车session中取得购物车数据,根据购物车数据创建订单对象和订单详情列表list集合

商品购物车是面向数据库中的 tb_order表和订单详情表tb_orderDetail,在订单预览界面添加数据到数据库中对应的表,

购物车建立对应的 CartServlet 类、CartService 接口和实现类、CartDao 接口和实现类。

订单建立对应的 OrderServlet 类、OrderService 接口和实现类、OrderDao 接口和实现类。

订单详情对应的 OrderDetailServlet 类、OrderDetailService 接口和实现类、OrderDetailDao 接口和实现类。

提示:好需要创建辅助的vo类

订单列表的显示需要一个vo类,其中包含订单信息和地址信息以及用户信息

OrderView : oid uid orderTime userName telphon address totalMoney ostate

GoodOrdersDetailVo: pid pimg pname star pubdate, price num money

3.1 前端 3.1.1 修改商品详情a链接地址 3.1.2修改order.html代码

    <script type="text/javascript">

        $(function () {
            $("#btn_add").click(function () {
                location.href = "order.do?action=generateOrder&aid=" +
                    $("#address").val();
            })
        });


        //获取购物车列表
        $(document).ready(function () {

            //获取session数据显示到页面
            $.get("cart.do?action=showCart", "", function (result) {
                if (result.flag === true) {//登录

                    var sum = 0;//计算总金额变量
                    var index = 1;
                    for (var i in result.data) {
                        var money = result.data[i].quantity * result.data[i].price;
                        var temp =
                            '     ' +
                            '                        ' + index + '' +
                            '                        ' + result.data[i].goodName + ' ' +
                            '                        ' + result.data[i].price + ' ' +
                            '                        ' + result.data[i].quantity + ' ' +
                            '                        $' + result.data[i].subtotal + ' ' +
                            '                    '
                        index++;
                        sum += result.data[i].subtotal;
                        $("#orderBody").append(temp)
                    }
                    $("#total").html("¥  : " + sum + "")
                }
            });
        });

        //获取地址列表

        $(document).ready(function () {

            //获取session数据显示到页面
            $.get("address.do?action=showAddress", "", function (result) {
                var addStr = '';
                var temp = '  ' +
                    ' ' +
                    ' 收货地址 ' +
                    ' ' + addStr + '' + '';

                $("#orderFoot").append(temp);

            });
        });



3.2后端 3.2.1后端AddressServlet

在 AddressServlet类中根据购物车信息创建订单数据


@WebServlet("/address.do")
public class AddressServlet extends BaseServlet {
    private ResultData resultData = new ResultData();

    /**
     * 显示收货地址列表
     *
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String showAddress(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();

        User user = (User) session.getAttribute(Constants.LOGINUSER);
        int userId = 0;

        userId = user.getId();

        resultData.setFlag(false);
        if (user == null) {
            return Constants.REDIRECT + "/login.html";
        } else {
            IAddressService service = new AddressServiceImpl();
            List<Address> addressList = service.queryDataByUid(userId);

            if (addressList != null && !addressList.isEmpty()) {
                resultData.setFlag(true);
                resultData.setData(addressList);
            }
        }

        String json = JSON.toJSONString(resultData);
        System.err.println(json);
        resp.setContentType("application/json;charset=utf-8");
        return json;
    }
}
3.1.2 OrdarServlet

在 OrderServlet 类中根据购物车信息创建订单数据


@WebServlet("/order.do")
public class OrderServlet extends BaseServlet {
    private ResultData resultData = new ResultData();


    public String generateOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean falg = false;
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute(Constants.LOGINUSER);
        String aidStr = req.getParameter("aid");
        int aid = 0;
        if (aidStr != null) {
            try {
                aid = Integer.parseInt(aidStr);
            } catch (Exception e) {
                return Constants.REDIRECT + "/self_info.html";
            }
        }
        Order order = new Order();

        if (user == null) {
            return Constants.REDIRECT + "/login.html";
        } else {
            Map<String, CartItem> cartItemMap = (Map<String, CartItem>) req.getSession().getAttribute(Constants.CART);

            if (cartItemMap != null && cartItemMap.size() >= 1) {
                //一个订单对应多条订单详情数据,
                int uid = user.getId();//用户id;

                String oid = RandomUtils.createOrderId();
                order.setId(oid);
                List<Cart> cartList = new ArrayList<>();
                List<OrderDetail> orderDetailList = new ArrayList<>();
                double totalMoney = 0.0;
                for (String pid : cartItemMap.keySet()) {
                    CartItem cartItem = cartItemMap.get(pid);
                    //将订单项添加到cart
                    Cart cart = new Cart(0, Integer.parseInt(cartItem.getGoodsId()), cartItem.getQuantity(), cartItem.getSubtotal());
                    OrderDetail orderDetail = new OrderDetail(0, oid, Integer.parseInt(cartItem.getGoodsId()), cartItem.getQuantity(), cartItem.getSubtotal());
                    cartList.add(cart);
                    orderDetailList.add(orderDetail);
                    //将订单项的数据添加到orderDetail
                    totalMoney += cartItem.getSubtotal();
                }
                order.setUid(uid);
                order.setStatus(0);
                order.setTime(RandomUtils.getNowTime());
                order.setMoney(totalMoney);

                IOrderService orderService = new OrderServiceImpl();
                falg = orderService.savaOrder(order, cartList, orderDetailList);
                //session.removeAttribute(Constants.CART);
            }
        }
        if (falg) {
            session.removeAttribute(Constants.CART);
            return Constants.REDIRECT + "/orderSuccess.html?oid=" + order.getId() + "&money=" + order.getMoney();
        } else {
            return Constants.REDIRECT + "error.html?msg=订单创建失败";
        }

    }

    public String getOrderInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resultData.setData(true);
        HttpSession session = req.getSession();
        Order order = (Order) session.getAttribute(Constants.ORDER);
        if (order == null) {
            resultData.setData(false);
        }
        resultData.setData(order);

        String json = JSON.toJSONString(resultData);
        System.out.println(json);
        resp.setContentType("application/json;charset=utf-8");
        return json;
    }

}

3.1.3 编写OrderServiceImpl代码

订单创建涉及到多张数据表,必须做事务控制:

public class OrderServiceImpl implements IOrderService {
    //......
    private IOrderDao orderDao = null;
    private ICartDao cartDao = null;
    private IOrderDetailDao orderDetailDao = null;

    public OrderServiceImpl() {
        orderDao = new OrderDaoImpl();
        cartDao = new CartDaoImpl();
        orderDetailDao = new OrderDetailDaoImpl();
    }
    
    @Override
    public boolean savaOrder(Order order, List<Cart> cartList, List<OrderDetail> orderDetailList) {
        DBUtils.beginTransaction();
        boolean isSuccess = false;
        int n1 = orderDao.addData(order);
        if (n1 >= 1) {
            int n2 = cartDao.addCartList(cartList);
            if (n2 == cartList.size()) {
                int n3 = orderDetailDao.addOrderDetailList(orderDetailList);
                if (n3 == orderDetailList.size()) {
                    isSuccess = true;
                    DBUtils.commit();
                }
            }
        }
        if (isSuccess) {
            DBUtils.rollback();
        }

        return isSuccess;
    }
    //.......
}

3.1.4编写OrderDaoImpl码


public class OrderDaoImpl implements IOrderDao {
    private QueryRunner runner = new QueryRunner(true);

    public OrderDaoImpl() {


    }

    @Override
    public int addData(Order order) {
        int update=0;
        String sql = "insert into tb_order(id,uid,money,status,time,aid)values(?,?,?,?,?,?)";
        try {
            update = runner.update(DBUtils.getConn(), sql, order.getId(), order.getUid(), order.getMoney()
                    , order.getStatus(), order.getTime(), order.getAid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return update;
    }
    @Override
    public List<Order> queryGoodsBySql(String sql, Object... parms) {
        List<Order> query = null;
        QueryRunner run = new QueryRunner(DBUtils.getDataSource());
        try {
            query = run.query(sql, parms, new BeanListHandler<>(Order.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;

    }
    //.....
}
3.1.5 编写CartDaoImpl代码
public class CartDaoImpl implements ICartDao {
    private QueryRunner runner = new QueryRunner();


    @Override
    public List<Cart> queryGoodsBySql(String sql, Object... parms) {
        List<Cart> query = null;
        QueryRunner run = new QueryRunner(DBUtils.getDataSource());
        try {
            query = run.query(sql, parms, new BeanListHandler<>(Cart.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public int addCartList(List<Cart> cartList) {
        int n = 0;
        String sql = "insert into tb_cart (pid,Num,money) values(?,?,?)";
        Object[][] parmes = new Object[cartList.size()][3];
        for (int i = 0; i < cartList.size(); i++) {
            Cart cart = cartList.get(i);
            parmes[i] = new Object[]{cart.getPid(), cart.getNum(), cart.getMoney()};
        }
        try {
            int[] batch = runner.batch(DBUtils.getConn(), sql, parmes);
            for (int num : batch) {
                n += num;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return n;
    }
}

3.1.6 编写OrderDetailDaoImpl代码

public class OrderDetailDaoImpl implements IOrderDetailDao {
    private  QueryRunner runner=new QueryRunner();
    
    @Override
    public List<OrderDetail> queryGoodsBySql(String sql, Object... parms) {
        List<OrderDetail> query = null;
        QueryRunner run = new QueryRunner(DBUtils.getDataSource());
        try {
            query = run.query(sql, parms, new BeanListHandler<>(OrderDetail.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    @Override
    public int addOrderDetailList(List<OrderDetail> orderDetailList) {
        int n = 0;
        String sql = "insert into tb_orderdetail (oid,pid,Num,money) values(?,?,?,?)";
        Object[][] parmes = new Object[orderDetailList.size()][4];
        for (int i = 0; i < orderDetailList.size(); i++) {
            OrderDetail cart = orderDetailList.get(i);
            parmes[i] = new Object[]{cart.getOid(),cart.getPid(), cart.getNum(), cart.getMoney()};
        }
        try {
            int[] batch = runner.batch(DBUtils.getConn(), sql, parmes);
            for (int num : batch) {
                n += num;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return n;
    }
}

OrderDetail cart = orderDetailList.get(i);
parmes[i] = new Object[]{cart.getOid(),cart.getPid(), cart.getNum(), cart.getMoney()};
}
try {
int[] batch = runner.batch(DBUtils.getConn(), sql, parmes);
for (int num : batch) {
n += num;
}
} catch (SQLException e) {
e.printStackTrace();
}

    return n;
}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1297751.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存