上一部分我们已经完成了购物车模块,这一部分我们完成订单模块,主要包括生成订单,查询所有订单,发货,查看订单详情,查看我的订单,签收订单。
订单模块的分析
订单模块的实现
创建订单模块的数据库表
为订单创建一个t_order表,为订单项创建一个t_order_item表。- use book;createtable t_order(`order_id`varchar(50)primarykey,`create_time`datetime,`price`decimal(11,2),`status`int,`user_id`int,foreignkey(`user_id`)references t_user(`id`));createtable t_order_item(`id`intprimarykeyauto_increment,`name`varchar(100),`count`int,`price`decimal(11,2),`total_price`decimal(11,2),`order_id`varchar(50),foreignkey(`order_id`)references t_order(`order_id`));
复制代码 创建订单模块的数据模型
创建一个Order类和一个OrderItem类,Order类属性如下:- privateString orderId;privateDate createTime;privateBigDecimal price;// 0未发货,1已发货,2已签收privateInteger status =0;privateInteger userId;
复制代码 OrderItem类属性如下:- privateInteger id;privateString name;privateInteger count;privateBigDecimal price;privateBigDecimal totalPrice;privateString orderId;
复制代码 并为其生成构造方法,Get方法,Set方法,以及toString方法。
编写订单模块的Dao程序和测试
OrderDao接口- publicinterfaceOrderDao{publicintsaveOrder(Order order);publicList<Order>queryOrders();publicList<Order>queryOrdersByUserId(Integer id);publicintupdateOrder(Order order);}
复制代码 OrderDaoImpl实现类- publicclassOrderDaoImplextendsBaseDaoimplementsOrderDao{/**
- * 保管订单
- * @param order
- * @return
- */@OverridepublicintsaveOrder(Order order){String sql ="insert into t_order(`order_id`,`create_time`,`price`,`status`,`user_id`) values(?,?,?,?,?)";returnupdate(sql, order.getOrderId(), order.getCreateTime(), order.getPrice(), order.getStatus(), order.getUserId());}/**
- * 查询全部订单
- * @return
- */@OverridepublicList<Order>queryOrders(){String sql ="select `order_id` orderId,`create_time` createTime,`price`,`status`,`user_id` userId from t_order";returnqueryForList(Order.class, sql);}/**
- * 根据UserId查询订单
- * @param id
- * @return
- */@OverridepublicList<Order>queryOrdersByUserId(Integer id){String sql ="select `order_id` orderId,`create_time` createTime,`price`,`status`,`user_id` userId from t_order where user_id=?";returnqueryForList(Order.class, sql, id);}/**
- * 修改订单
- * @param order
- * @return
- */@OverridepublicintupdateOrder(Order order){String sql ="update t_order set `create_time`=?,`price`=?,`status`=? where order_id=?";returnupdate(sql, order.getCreateTime(), order.getPrice(), order.getStatus(), order.getOrderId());}}
复制代码 测试- publicclassOrderDaoTest{OrderDao orderDao =newOrderDaoImpl();@TestpublicvoidsaveOrder(){
- orderDao.saveOrder(newOrder("12345678",newDate(),newBigDecimal(100),0,2));
- orderDao.saveOrder(newOrder("123",newDate(),newBigDecimal(1005),0,5));
- orderDao.saveOrder(newOrder("456",newDate(),newBigDecimal(505),1,6));
- orderDao.saveOrder(newOrder("789",newDate(),newBigDecimal(605),2,6));}@TestpublicvoidqueryOrders(){System.out.println(orderDao.queryOrders());}@TestpublicvoidqueryOrdersByUserId(){System.out.println(orderDao.queryOrdersByUserId(6));}@TestpublicvoidupdateOrder(){
- orderDao.updateOrder(newOrder("456",newDate(),newBigDecimal(611),2,6));}}
复制代码 OrderDaoItem接口- publicinterfaceOrderItemDao{publicintsaveOrderItem(OrderItem orderItem);publicList<OrderItem>queryOrderItemsById(String id);}
复制代码 OrderDaoItemImpl实现类- publicclassOrderItemDaoImplextendsBaseDaoimplementsOrderItemDao{/**
- * 保管订单项
- * @param orderItem
- * @return
- */@OverridepublicintsaveOrderItem(OrderItem orderItem){String sql ="insert into t_order_item(`name`,`count`,`price`,`total_price`,`order_id`) values(?,?,?,?,?)";returnupdate(sql, orderItem.getName(), orderItem.getCount(), orderItem.getPrice(), orderItem.getTotalPrice(), orderItem.getOrderId());}/**
- * 根据order_id查询订单项
- * @param id
- * @return
- */@OverridepublicList<OrderItem>queryOrderItemsById(String id){String sql ="select `id`,`name`,`count`,`price`,`total_price` totalPrice,`order_id` orderId from t_order_item where order_id=?";returnqueryForList(OrderItem.class, sql, id);}}
复制代码 测试- publicclassOrderItemDaoTest{OrderItemDao orderItemDao =newOrderItemDaoImpl();@TestpublicvoidsaveOrderItem(){
- orderItemDao.saveOrderItem(newOrderItem(null,"java 从入门到通晓",1,newBigDecimal(100),newBigDecimal(100),"456"));
- orderItemDao.saveOrderItem(newOrderItem(null,"javaScript 从入门到通晓",2,newBigDecimal(100),newBigDecimal(200),"12345678"));
- orderItemDao.saveOrderItem(newOrderItem(null,"Netty 入门",1,newBigDecimal(100),newBigDecimal(100),"456"));}@TestpublicvoidqueryOrderItemsById(){System.out.println(orderItemDao.queryOrderItemsById("12345678"));}}
复制代码 编写订单模块的Service和测试
OrderService接口- publicinterfaceOrderService{/**
- * 创建订单
- * @param cart
- * @param userId
- * @return
- */publicStringcreateOrder(Cart cart,Integer userId);/**
- * 展示所有订单
- * @return
- */publicList<Order>showAllOrders();/**
- * 发货
- * @param order
- */publicvoidsendOrder(Order order);/**
- * 查询订单详情
- * @param id
- * @return
- */publicList<OrderItem>showOrderDetail(String id);/**
- * 展示我的订单
- * @param id
- * @return
- */publicList<Order>showMyOrders(Integer id);/**
- * 签收
- * @param order
- */publicvoidreceiverOrder(Order order);}
复制代码 OrderServiceImpl实现类- publicclassOrderServiceImplimplementsOrderService{privateOrderDao orderDao =newOrderDaoImpl();privateOrderItemDao orderItemDao =newOrderItemDaoImpl();privateBookDao bookDao =newBookDaoImpl();@OverridepublicStringcreateOrder(Cart cart,Integer userId){// 订单号==唯一性String orderId =System.currentTimeMillis()+""+userId;// 创建一个订单对象Order order =newOrder(orderId,newDate(), cart.getTotalPrice(),0, userId);// 保管订单
- orderDao.saveOrder(order);// 遍历购物车中每一个商品项转换成为订单项保管到数据库for(Map.Entry<Integer,CartItem>entry : cart.getItems().entrySet()){// 获取每一个购物车中的商品项CartItem cartItem = entry.getValue();// 转换为每一个订单项OrderItem orderItem =newOrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalprice(), orderId);// 保管订单项到数据库
- orderItemDao.saveOrderItem(orderItem);// 更新库存和销量Book book = bookDao.queryBookById(cartItem.getId());
- book.setSales( book.getSales()+ cartItem.getCount());
- book.setStock( book.getStock()- cartItem.getCount());
- bookDao.updateBook(book);}// 清空购物车
- cart.clear();return orderId;}@OverridepublicList<Order>showAllOrders(){return orderDao.queryOrders();}@OverridepublicvoidsendOrder(Order order ){
- order.setStatus(1);
- orderDao.updateOrder(order);}@OverridepublicList<OrderItem>showOrderDetail(String id){return orderItemDao.queryOrderItemsById(id);}@OverridepublicList<Order>showMyOrders(Integer id){return orderDao.queryOrdersByUserId(id);}@OverridepublicvoidreceiverOrder(Order order){
- order.setStatus(2);
- orderDao.updateOrder(order);}}
复制代码 测试- publicclassOrderServiceImplTest{privateOrderService orderService =newOrderServiceImpl();@TestpublicvoidcreateOrder(){Cart cart =newCart();
- cart.addItem(newCartItem(1,"java从入门到通晓",1,newBigDecimal(1000),newBigDecimal(1000)));
- cart.addItem(newCartItem(1,"java从入门到通晓",1,newBigDecimal(1000),newBigDecimal(1000)));
- cart.addItem(newCartItem(2,"数据构造与算法",1,newBigDecimal(100),newBigDecimal(100)));System.out.println("订单号是:"+ orderService.createOrder(cart,2));}@TestpublicvoidshowAllOrders(){System.out.println(orderService.showAllOrders());}@TestpublicvoidsendOrder(){
- orderService.sendOrder(newOrder("16366346078552",newDate(),newBigDecimal(2100),0,2));}@TestpublicvoidshowOrderDetail(){System.out.println(orderService.showOrderDetail("16366346078552"));}@TestpublicvoidshowMyOrders(){System.out.println(orderService.showMyOrders(2));}@TestpublicvoidreceiverOrder(){
- orderService.receiverOrder(newOrder("16366346078552",newDate(),newBigDecimal(2100),1,2));}}
复制代码 编写订单模块的Web层和页面联调
生成订单
OrderServlet添加createOrder方法
- /**
- * 生成订单
- * @param req
- * @param resp
- * @throws ServletException
- * @throws IOException
- */protectedvoidcreateOrder(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{// 先获取购物车对象Cart cart =(Cart) req.getSession().getAttribute("cart");// 获取UseridUser loginUser =(User) req.getSession().getAttribute("user");if(loginUser ==null){
- req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);return;}Integer userId = loginUser.getId();String orderId = orderService.createOrder(cart, userId);
- req.getSession().setAttribute("orderId",orderId);
- resp.sendRedirect(req.getContextPath()+"/pages/cart/checkout.jsp");}
复制代码修改cart.jsp页面,结账的恳求地址
修改checkout.jsp页面
展示全部订单
OrderServlet添加showAllOrders方法
- /**
- * 展示全部订单
- * @param req
- * @param resp
- * @throws ServletException
- * @throws IOException
- */protectedvoidshowAllOrders(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{// 1.通过orderService查询所有订单List<Order> orders = orderService.showAllOrders();// 2.把全部订单保管到Request域
- req.setAttribute("orders", orders);// 3.恳求转发到 /pages/manager/order_manager.jsp
- req.getRequestDispatcher("/pages/manager/order_manager.jsp");}
复制代码修改manager_menu.jsp页面,订单管理恳求地址
修改order_manager.jsp页面
展示我的订单
OrderServlet添加showMyOrders方法
- /**
- * 展示我的订单
- * @param req
- * @param resp
- * @throws ServletException
- * @throws IOException
- */protectedvoidshowMyOrders(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{// 获取UseridUser loginUser =(User) req.getSession().getAttribute("user");if(loginUser ==null){
- req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);return;}Integer userId = loginUser.getId();List<Order> myOrders = orderService.showMyOrders(userId);
- req.getSession().setAttribute("myOrders", myOrders);
- resp.sendRedirect(req.getContextPath()+"/pages/order/order.jsp");}
复制代码修改login_success_menu.jsp页面,我的订单恳求地址
修改order.jsp页面
显示订单详情
OrderServlet增加showOrderDetail方法
- /**
- * 显示订单详情
- * @param req
- * @param resp
- * @throws ServletException
- * @throws IOException
- */protectedvoidshowOrderDetail(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{// 1. 获取OrderidString orderId = req.getParameter("orderId");if(orderId !=null&& orderId !=""){// 2. 查询订单项List<OrderItem> orderItems = orderService.showOrderDetail(orderId);// 3. 把订单项保管到Request域
- req.setAttribute("orderItems", orderItems);// 4. 恳求转发到 /pages/order/order_detail.jsp
- req.getRequestDispatcher("/pages/order/order_detail.jsp").forward(req, resp);}}
复制代码在order目录下新建order_detail.jsp页面
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ page contentType="text/html;charset=UTF-8" language="java"%><!DOCTYPE html><html><head><meta charset="UTF-8"><title>我的订单</title><%-- 静态包含 base标签,css款式,jQuery文件 --%><%@ include file="/pages/common/head.jsp"%><style type="text/css">
- h1 {
- text-align: center;
- margin-top:200px;}</style></head><body><div id="header"><img class="logo_img" alt="" src="static/img/logo.gif"><span class="wel_word">我的订单</span><%-- 静态包含登录胜利之后的菜单 --%><%@ include file="/pages/common/login_success_menu.jsp"%></div><div id="main"><table><tr><td>商品名称</td><td>数量</td><td>单价</td><td>金额</td></tr><c:forEach items="${requestScope.orderItems}"var="orderItem"><tr><td>${orderItem.name}</td><td>${orderItem.count}</td><td>${orderItem.price}</td><td>${orderItem.totalPrice}</td></tr></c:forEach></table></div><%-- include包含脚部信息 --%><%@ include file="/pages/common/footer.jsp"%></body></html>
复制代码修改order.jsp页面,查看详情恳求地址
修改order_manager.jsp页面,查看详情恳求地址
发货
OrderServlet增加sendOrder方法
- /**
- * 发货
- * @param req
- * @param resp
- * @throws ServletException
- * @throws IOException
- */protectedvoidsendOrder(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{// 1. 获取OrderOrder order =WebUtils.copyParamToBean(req.getParameterMap(),newOrder());// 2. 调用orderService的sendOrder方法发货
- orderService.sendOrder(order);// 3. 重定向回 /pages/manager/order_manager.jsp
- resp.sendRedirect(req.getContextPath()+"/pages/manager/order_manager.jsp");}
复制代码修改WebUtils的copyParamToBean方法,因为BeanUtils无法直接将String转为Date,所以要先注册
修改order_manager.jsp页面, 点击发货恳求地址
签收
OrderServlet增加receiverOrder方法
- /**
- * 签收
- * @param req
- * @param resp
- * @throws ServletException
- * @throws IOException
- */protectedvoidreceiverOrder(HttpServletRequest req,HttpServletResponse resp)throwsServletException,IOException{// 1. 获取OrderOrder order =WebUtils.copyParamToBean(req.getParameterMap(),newOrder());// 2. 调用orderService的receiverOrder方法签收
- orderService.receiverOrder(order);// 3. 重定向回 /orderServlet?action=showMyOrders
- resp.sendRedirect(req.getContextPath()+"/orderServlet?action=showMyOrders");}
复制代码 |