• (二十)生成订单


    案例4-生成订单
    需求:
        在购物车页面上,有i一个提交订单,点击的时候,将用户购物车中的商品添加到数据库中.
    实体:
        用户
        订单
        订单项(中间表)
        商品

    需要在order实体提供 user对象和list<OrderItem>
    需要在orderItem实体中提供 product对象和order对象

    步骤分析:
    点击生成订单:
      /store/order?method=add
    创建OrderServlet
      add方法中:
        1.判断用户是否登录,
        2.封装数据 Order
        oid      随机
        total   购物车中的总金额
        ordertime   当前时间

           User     session中当前用户

           订单项集合List<OrderItem>
          创建OrderItem,然后添加到list中
          orderItem从那里来????????/
            购物车中CartItem

        name(先不管)
        address(先不管)
        telephone(先不管)
      3.调用orderservice 生成订单
        开启事务
        先往订单表中插入一条数据
        往订单项表中插入n条数据
        提交事务

    创建表

    订单表
            CREATE TABLE `orders` (
              `oid` varchar(32) NOT NULL,
              `ordertime` datetime DEFAULT NULL,
              `total` double DEFAULT NULL,
              `state` int(11) DEFAULT NULL,
              `address` varchar(30) DEFAULT NULL,
              `name` varchar(20) DEFAULT NULL,
              `telephone` varchar(20) DEFAULT NULL,
              `uid` varchar(32) DEFAULT NULL,
              PRIMARY KEY (`oid`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     订单项表
            CREATE TABLE `orderitem` (
              `itemid` varchar(32) NOT NULL,
              `count` int(11) DEFAULT NULL,
              `subtotal` double DEFAULT NULL,
              `pid` varchar(32) DEFAULT NULL,
              `oid` varchar(32) DEFAULT NULL,
              PRIMARY KEY (`itemid`),
              KEY `fk_0001` (`pid`),
              KEY `fk_0002` (`oid`),
              CONSTRAINT `fk_0001` FOREIGN KEY (`pid`) REFERENCES `product` (`pid`),
              CONSTRAINT `fk_0002` FOREIGN KEY (`oid`) REFERENCES `orders` (`oid`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    创建bean

    com.louis.domain.Order

    package com.louis.domain;
    
    import java.io.Serializable;
    import java.util.Date;
    import java.util.LinkedList;
    import java.util.List;
    
    public class Order implements Serializable{
    /*
     * `oid` varchar(32) NOT NULL,
      `ordertime` datetime DEFAULT NULL,
      `total` double DEFAULT NULL,
      
      `state` int(11) DEFAULT NULL,
      `address` varchar(30) DEFAULT NULL,
      `name` varchar(20) DEFAULT NULL,
      
      `telephone` varchar(20) DEFAULT NULL,
      `uid` varchar(32) DEFAULT NULL,
     */
        private String oid;
        private Date ordertime;
        private Double total;
        
        private Integer state=0;//订单状态  0:未支付  1:已支付 
        private String address;
        private String name;
        
        private String telephone;
        
        //属于那个用户
        private User user;
        
    
        //包含那些订单项
        private List<OrderItem> items=new LinkedList<>();
        
         //“属于”对应mysql中的字段,"包含"则不用,但“被包含”会对应mysql字段
        
        public String getOid() {
            return oid;
        }
    
        public void setOid(String oid) {
            this.oid = oid;
        }
    
        public Date getOrdertime() {
            return ordertime;
        }
    
        public void setOrdertime(Date ordertime) {
            this.ordertime = ordertime;
        }
    
        public Double getTotal() {
            return total;
        }
    
        public void setTotal(Double total) {
            this.total = total;
        }
    
        public Integer getState() {
            return state;
        }
    
        public void setState(Integer state) {
            this.state = state;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getTelephone() {
            return telephone;
        }
    
        public void setTelephone(String telephone) {
            this.telephone = telephone;
        }
    
        public User getUser() {
            return user;
        }
    
        public void setUser(User user) {
            this.user = user;
        }
    
        public List<OrderItem> getItems() {
            return items;
        }
    
        public void setItems(List<OrderItem> items) {
            this.items = items;
        }
    
    }

    com.louis.domain.OrderItem

    package com.louis.domain;
    
    import java.io.Serializable;
    
    public class OrderItem implements Serializable{
    /**
     * `itemid` varchar(32) NOT NULL,
      `count` int(11) DEFAULT NULL,
      `subtotal` double DEFAULT NULL,
      `pid` varchar(32) DEFAULT NULL,
      `oid` varchar(32) DEFAULT NULL,
     */
        
        private String itemid;
        private Integer count;
        private Double subtotal;
        
        //包含那个商品
        private Product product;
        
        //属于那个订单
        private Order order;
    
        public String getItemid() {
            return itemid;
        }
    
        public void setItemid(String itemid) {
            this.itemid = itemid;
        }
    
        public Integer getCount() {
            return count;
        }
    
        public void setCount(Integer count) {
            this.count = count;
        }
    
        public Double getSubtotal() {
            return subtotal;
        }
    
        public void setSubtotal(Double subtotal) {
            this.subtotal = subtotal;
        }
    
        public Product getProduct() {
            return product;
        }
    
        public void setProduct(Product product) {
            this.product = product;
        }
    
        public Order getOrder() {
            return order;
        }
    
        public void setOrder(Order order) {
            this.order = order;
        }
        
        
    }

     /store/src/beans.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans>
        <bean id="CategoryService" class="com.louis.service.impl.CategoryServiceImpl"></bean>
        <bean id="ProductService" class="com.louis.service.impl.ProductServiceImpl"></bean>
        <bean id="UserService" class="com.louis.service.impl.UserServiceImpl"></bean>
        <bean id="OrderService" class="com.louis.service.impl.OrderServiceImpl"></bean>
    
       <bean id="ProductDao" class="com.louis.dao.impl.ProductDaoImpl"/>
       <bean id="UserDao" class="com.louis.dao.impl.UserDaoImpl"/>
       <bean id="CategoryDao" class="com.louis.dao.impl.CategoryDaoImpl"/>
       <bean id="OrderDao" class="com.louis.dao.impl.OrderDaoImpl"/>
       
    </beans>

    /store/WebContent/jsp/cart.jsp

                  <a href="${pageContext.request.contextPath }/order?method=add">
                                <input type="submit" width="100" value="提交订单" name="submit" border="0" style="background: url('${pageContext.request.contextPath}/images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
                                height:35px;100px;color:white;">
                            </a>

    com.louis.web.servlet.OrderServlet

    package com.louis.web.servlet;
    
    import java.io.IOException;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.beanutils.ConvertUtils;
    
    import com.louis.domain.Cart;
    import com.louis.domain.CartItem;
    import com.louis.domain.Order;
    import com.louis.domain.OrderItem;
    import com.louis.domain.Product;
    import com.louis.domain.User;
    import com.louis.myconvertor.MyConverter;
    import com.louis.service.OrderService;
    import com.louis.service.ProductService;
    import com.louis.service.impl.OrderServiceImpl;
    import com.louis.service.impl.ProductServiceImpl;
    import com.louis.utils.BeanFactory;
    import com.louis.utils.UUIDUtils;
    
    import net.sf.ehcache.search.expression.Between;
    
    
    public class OrderServlet extends BaseServlet {
        public String add(HttpServletRequest request, HttpServletResponse response) throws Exception {
            //0.判断用户是否登录
            User user=(User) request.getSession().getAttribute("user");
            if(user == null){
                request.setAttribute("msg", "请先登录~~");
                return "/jsp/msg.jsp";
            }
            
            //1.封装数据
            Order order=new Order();
            //1.1 订单id
            order.setOid(UUIDUtils.getId());
            
            //1.2 订单时间
             DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
            order.setOrdertime(dateFormat2.parse("2010-09-13 22:36:01"));
            
            //1.3 总金额
            //获取session中cart
            Cart cart=(Cart) request.getSession().getAttribute("cart");
            
            order.setTotal(cart.getTotal());
            
            //1.4 订单的所有订单项
            /*
             * 先获取cart中itmes
             * 遍历itmes 组装成orderItem
             * 将orderItem添加到list(items)中
             */
            for (CartItem cartItem : cart.getItmes()) {
                OrderItem oi = new OrderItem();
                
                //设置id
                oi.setItemid(UUIDUtils.getId());
                
                //设置购买数量
                oi.setCount(cartItem.getCount());
                
                //设置小计
                oi.setSubtotal(cartItem.getSubtotal());
                
                //设置product
                oi.setProduct(cartItem.getProduct());
                
                //设置order
                oi.setOrder(order);
                
                //添加到list中
                order.getItems().add(oi);
            }
            
            //1.5 设置用户
            order.setUser(user);
            
            //2.调用service 添加订单
            OrderService os=(OrderService) BeanFactory.getBean("OrderService");
            os.add(order);
            
            //3.将order放入request域中,请求转发
            request.setAttribute("bean", order);
            
            //4.清空购物车,不清空的话,下次购买上次的商品还在购物车内
            request.getSession().removeAttribute("cart");
            return "/jsp/order_info.jsp";
        }
    }

    /store/WebContent/WEB-INF/web.xml

    <servlet>
        <description></description>
        <display-name>OrderServlet</display-name>
        <servlet-name>OrderServlet</servlet-name>
        <servlet-class>com.louis.web.servlet.OrderServlet</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>OrderServlet</servlet-name>
        <url-pattern>/order</url-pattern>
      </servlet-mapping>

    com.louis.service.impl.OrderServiceImpl

    package com.louis.service.impl;
    
    import com.louis.dao.OrderDao;
    import com.louis.domain.Order;
    import com.louis.domain.OrderItem;
    import com.louis.service.OrderService;
    import com.louis.utils.BeanFactory;
    import com.louis.utils.DataSourceUtils;
    
    public class OrderServiceImpl implements OrderService {
    
        @Override
        public void add(Order order) throws Exception {
            try {
                //1、开启事务
                DataSourceUtils.startTransaction();
                OrderDao orderDao = (OrderDao) BeanFactory.getBean("OrderDao");
                //2、向order表中添加一个数据
                orderDao.add(order);
                //3、向orderItem中添加n条数据
                for(OrderItem orderItem : order.getItems()) {
                    orderDao.addItem(orderItem);
                }
                //4、事务处理
                DataSourceUtils.commitAndClose();
            } catch (Exception e) {
                e.printStackTrace();
                DataSourceUtils.rollbackAndClose();
                throw e;
            }
            
            
        }
    
    }

    com.louis.dao.impl.OrderDaoImpl

    package com.louis.dao.impl;
    
    import org.apache.commons.dbutils.QueryRunner;
    
    import com.louis.dao.OrderDao;
    import com.louis.domain.Order;
    import com.louis.domain.OrderItem;
    import com.louis.utils.DataSourceUtils;
    
    public class OrderDaoImpl implements OrderDao {
    
        /**
         * 添加一条订单
         */
        @Override
        public void add(Order order) throws Exception {
            //如果带有参数,则是自动开启事务,整体事务会出现问题
            QueryRunner qr = new QueryRunner();
            
            /*
             * `oid` varchar(32) NOT NULL,
              `ordertime` datetime DEFAULT NULL,
              `total` double DEFAULT NULL,
              
              `state` int(11) DEFAULT NULL,
              `address` varchar(30) DEFAULT NULL,
              `name` varchar(20) DEFAULT NULL,
              
              `telephone` varchar(20) DEFAULT NULL,
              `uid` varchar(32) DEFAULT NULL,
             */
            String sql="insert into orders values(?,?,?,?,?,?,?,?)";
            qr.update(DataSourceUtils.getConnection(),sql, order.getOid(),order.getOrdertime(),order.getTotal(),order.getState(),
                    order.getAddress(),order.getName(),order.getTelephone(),order.getUser().getUid());
        }
    
        /**
         * 添加一条订单项
         */
        @Override
        public void addItem(OrderItem oi) throws Exception {
            QueryRunner qr = new QueryRunner();
             /**
             * `itemid` varchar(32) NOT NULL,
              `count` int(11) DEFAULT NULL,
              `subtotal` double DEFAULT NULL,
              `pid` varchar(32) DEFAULT NULL,
              `oid` varchar(32) DEFAULT NULL,
             */
            String sql="insert into orderitem values(?,?,?,?,?)";
            qr.update(DataSourceUtils.getConnection(),sql, oi.getItemid(),oi.getCount(),oi.getSubtotal(),oi.getProduct().getPid(),oi.getOrder().getOid());
        }
    
    }

    /store/WebContent/jsp/order_info.jsp

    <div style="margin:0 auto;margin-top:10px;950px;">
                        <strong>订单详情</strong>
                        <table class="table table-bordered">
                            <tbody>
                                <tr class="warning">
                                    <th colspan="5">订单编号:${bean.oid } </th>
                                </tr>
                                <tr class="warning">
                                    <th>图片</th>
                                    <th>商品</th>
                                    <th>价格</th>
                                    <th>数量</th>
                                    <th>小计</th>
                                </tr>
                                <c:forEach items="${bean.items }" var="oi">
                                    <tr class="active">
                                        <td width="60" width="40%">
                                            <input type="hidden" name="id" value="22">
                                            <img src="${pageContext.request.contextPath}/${oi.product.pimage}" width="70" height="60">
                                        </td>
                                        <td width="30%">
                                            <a target="_blank">${oi.product.pname }</a>
                                        </td>
                                        <td width="20%">
                                            ¥${oi.product.shop_price }
                                        </td>
                                        <td width="10%">
                                            ${oi.count }
                                        </td>
                                        <td width="15%">
                                            <span class="subtotal">¥${oi.subtotal }</span>
                                        </td>
                                    </tr>
                                </c:forEach>
                            </tbody>
                        </table>
                    </div>

    问题

    1、mysql主键外键

    2、Sat Oct 14 21:47:13 CST 2017

      http://blog.csdn.net/u010003835/article/details/50435058

  • 相关阅读:
    HDU2473 Junk-Mail Filter 【可删除的并查集】
    NOI2001 食物链【扩展域并查集】*
    POJ1733 Parity game 【扩展域并查集】*
    Codeforces 9D How many trees? 【计数类DP】
    Codeforces 28C Bath Queue 【计数类DP】*
    Codeforces 280C Game on tree【概率DP】
    Codeforces 914H Ember and Storm's Tree Game 【DP】*
    Codeforces 1027E Inverse Coloring 【DP】
    BZOJ3673 可持久化并查集 by zky 【主席树】
    BZOJ4561 JLoi2016 圆的异或并 【扫描线】【set】*
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7668333.html
Copyright © 2020-2023  润新知