大项目之网上书城(九)——订单Demo

大项目之网上书城(九)——订单Demo

主要改动

加了创建订单,为订单付款,删除订单。

1.OrderServiceImpl

代码

有添加、删除、付款、根据是否付款查找。还加了添加收货信息登记。

package cn.edu.bdu.mc.services.impls;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.edu.bdu.mc.beans.Book;
import cn.edu.bdu.mc.beans.Order;
import cn.edu.bdu.mc.beans.Orderitem;
import cn.edu.bdu.mc.daos.BookDao;
import cn.edu.bdu.mc.daos.OrderDao;
import cn.edu.bdu.mc.daos.OrderitemDao;
import cn.edu.bdu.mc.daos.impls.BookDaoImpl;
import cn.edu.bdu.mc.daos.impls.OrderDaoImpl;
import cn.edu.bdu.mc.daos.impls.OrderitemDaoImpl;
import cn.edu.bdu.mc.services.OrderService;

public class OrderServiceImpl implements OrderService {
    
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderitemDao orderitemDao  = new OrderitemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();
    
    @Override
    public boolean addOrder(String order_id, int user_id, String name, String address, String phone, String[] book_ids) throws SQLException {
        // TODO Auto-generated method stub
        List<Book>books = new ArrayList<Book>();
        for (String book_id : book_ids) {   
            Book book = bookDao.findBookById(Integer.parseInt(book_id));
            books.add(book);
            //如果数量不够了就本次购买失败
            if(book.getCount()==0) {
                return false;
            }
        }
        Order order = new Order();
        order.setUser_id(user_id);
        order.setReciver_name(name);
        order.setReciver_phone(phone);
        order.setReciver_address(address);
        order.setOrder_id(order_id);
        orderDao.addOrder(order);
        for (Book book : books) {           
            Orderitem orderitem = new Orderitem();
            orderitem.setBook_id(book.getBook_id());
            orderitem.setOrder_id(order_id);
            orderitem.setCount(1);
            orderitem.setPrice(book.getPrice());
            book.setCount(book.getCount()-1);
            bookDao.update(book);
            orderitemDao.addOrderitem(orderitem);
        }
        return true;
    }
    
    @Override
    public void AfterPay(String order_id) throws SQLException {
        Order order = orderDao.findOrderById(order_id);
        order.setPaystate(1);
        orderDao.update(order);
    }

    @Override
    public Order delById(String order_id) throws SQLException {
        // TODO Auto-generated method stub
        Order order = orderDao.delById(order_id);
        orderitemDao.delById(order_id);
        return order;
    }

    @Override
    public List<Order> findNotPayByUser_id(int user_id) throws SQLException {
        // TODO Auto-generated method stub
        return orderDao.findOrderByUser_id(user_id, 0);
    }

    @Override
    public List<Order> findAreadyPayByUser_id(int user_id) throws SQLException {
        // TODO Auto-generated method stub
        return orderDao.findOrderByUser_id(user_id, 1);
    }

    
}

2.OrderDaoImpl

代码

目前有添加、删除、根据order_id查找和根据user_id查找

package cn.edu.bdu.mc.daos.impls;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.edu.bdu.mc.beans.Order;
import cn.edu.bdu.mc.daos.OrderDao;
import cn.edu.bdu.mc.utils.JDBCUtil;

public class OrderDaoImpl implements OrderDao {

    private DataSource dataSource = JDBCUtil.getDataSource();
    private QueryRunner queryRunner = new QueryRunner(dataSource);      
    
    @Override
    public void addOrder(Order order) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "insert into `order`(user_id,order_id,reciver_name,reciver_phone,reciver_address,paystate,money,order_time) values(?,?,?,?,?,0,0,?)";
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        String date1 = dateFormat.format(date);
        queryRunner.update(sql,order.getUser_id(),order.getOrder_id(),order.getReciver_name(),order.getReciver_phone(),order.getReciver_address(),date1);
    }
    
    @Override
    public void update(Order order) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "update `order` set user_id = ?,reciver_name = ?,reciver_phone = ?,reciver_address = ?,paystate = ?,money = ?,order_time = ?";
        queryRunner.update(sql,order.getUser_id(),order.getReciver_name(),order.getReciver_phone(),order.getReciver_address(),order.getPaystate(),order.getMoney(),order.getOrder_time());
    }

    @Override
    public Order findOrderById(String order_id) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "select * from `order` where order_id = ?";
        return queryRunner.query(sql, new BeanHandler<Order>(Order.class), order_id);
    }

    @Override
    public Order delById(String order_id) throws SQLException {
        Order order = findOrderById(order_id);
        String sql = "delete from `order` where order_id = ?";
        queryRunner.update(sql, order_id);
        return order;
    }

    @Override
    public List<Order> findOrderByUser_id(int user_id, int paystate) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "select * from `order` where user_id = ? and paystate = ?";
        return queryRunner.query(sql, new BeanListHandler<Order>(Order.class), user_id, paystate);
    }
    
    

}

3.OrderitemDaoImpl

代码

目前有添加和删除

package cn.edu.bdu.mc.daos.impls;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import cn.edu.bdu.mc.beans.Orderitem;
import cn.edu.bdu.mc.daos.OrderitemDao;
import cn.edu.bdu.mc.utils.JDBCUtil;

public class OrderitemDaoImpl implements OrderitemDao {

    private DataSource dataSource = JDBCUtil.getDataSource();
    private QueryRunner queryRunner = new QueryRunner(dataSource);      

    @Override
    public void addOrderitem(Orderitem orderitem) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "insert into orderitem values (?,?,?,?)";
        queryRunner.update(sql,orderitem.getOrder_id(),orderitem.getBook_id(),orderitem.getCount(),orderitem.getPrice());
    }

    @Override
    public void delById(String order_id) throws SQLException {
        // TODO Auto-generated method stub
        String sql = "delete from `order` where order_id = ?";
        queryRunner.update(sql, order_id);
    }

}

4.orderitem_insert触发器

代码

orderitem中每增加一项,将他对应的order_id的订单的钱增加上他的书的价格乘以数量。

DROP TRIGGER IF EXISTS `orderitem_insert`;
DELIMITER ;;
CREATE TRIGGER `orderitem_insert` AFTER INSERT ON `orderitem` FOR EACH ROW begin
    update `order` set money = money + new.price * new.count where order_id = new.order_id;
end
;;
DELIMITER ;

5.DelOrderServlet

代码

package cn.edu.bdu.mc.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.bdu.mc.beans.Order;
import cn.edu.bdu.mc.services.OrderService;
import cn.edu.bdu.mc.services.impls.OrderServiceImpl;

/**
 * Servlet implementation class DelOrderServlet
 */
@WebServlet("/DelOrder")
public class DelOrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DelOrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String order_id = request.getParameter("order_id");
            OrderService orderService = new OrderServiceImpl();
            Order order = orderService.delById(order_id);
            response.sendRedirect(request.getContextPath()+"/client/order.jsp");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

6.NewOrderServlet

代码

package cn.edu.bdu.mc.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.bdu.mc.beans.Order;
import cn.edu.bdu.mc.beans.User;
import cn.edu.bdu.mc.services.OrderService;
import cn.edu.bdu.mc.services.impls.OrderServiceImpl;

/**
 * Servlet implementation class NewOrderServlet
 */
@WebServlet("/NewOrder")
public class NewOrderServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewOrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(request.getSession().getAttribute("shouhuo")==null) {
            response.sendRedirect(request.getContextPath()+"/client/shouhuo.jsp");
        }else {
            try {
                String[] book_ids = request.getParameter("book_id_list").split("#");
                User user = (User) request.getSession().getAttribute("user");
                int user_id = user.getUser_id();
                Map<String, String>shouhuo = (Map<String, String>) request.getSession().getAttribute("shouhuo");
                String name = shouhuo.get("name");
                String phone = shouhuo.get("phone");
                String address = shouhuo.get("address");
                OrderService orderService = new OrderServiceImpl();
                String order_id = UUID.randomUUID().toString();
                boolean create_order = orderService.addOrder(order_id, user_id, name, address, phone, book_ids);
                if(create_order) {
                    String htmlCode="<!DOCTYPE html>\n" + 
                            "<html>"
                            + "<head>"
                            + "<link rel=\"stylesheet\" href=\""+request.getContextPath()+"/bootstrap-3.3.7-dist/css/bootstrap.min.css\">"
                            + "</head>"
                            + "<body>"
                            + "<div style=\"position:absolute;left:44%;top:42%;height:140px;width:240px;background-color:rgba(145, 162, 196, 0.9);border:1px;text-align:center;\"id=\"quit1\">\r\n" + 
                            "   <h3>订单创建成功!请尽快付款!</h3><a class=\"btn btn-info\" href=\""+request.getContextPath()+"/client/order.jsp\">查看订单</a>&nbsp;&nbsp;&nbsp;&nbsp;"
                            +"<a class=\"btn btn-info\" href=\""+request.getContextPath()+"/PayFor?order_id=\""+order_id+">立即付款</a>\n" + 
                            "</div>"
                            + "</body>"
                            + "</html>";
                    response.getWriter().write(htmlCode);
                }else {
                    String htmlCode="<!DOCTYPE html>\n" + 
                            "<html>"
                            + "<head>"
                            + "<link rel=\"stylesheet\" href=\""+request.getContextPath()+"/bootstrap-3.3.7-dist/css/bootstrap.min.css\">"
                            + "</head>"
                            + "<body>"
                            + "<div style=\"position:absolute;left:44%;top:46%;height:100px;width:240px;background-color:rgba(145, 162, 196, 0.9);border:1px;text-align:center;\"id=\"quit1\">\r\n" + 
                            "   <h3>订单创建失败!请检查订单!</h3><a class=\"btn btn-info\" href=\""+request.getContextPath()+"/client/order.jsp\">查看订单</a>&nbsp;&nbsp;&nbsp;&nbsp;"
                            +"<a class=\"btn btn-info\" href=\""+request.getContextPath()+"/client/index.jsp\">再逛逛</a>\n" + 
                            "</div>"
                            + "</body>"
                            + "</html>";
                    response.getWriter().write(htmlCode);
                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

7.PayForServlet

代码

package cn.edu.bdu.mc.servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.bdu.mc.beans.Order;
import cn.edu.bdu.mc.beans.User;
import cn.edu.bdu.mc.daos.OrderDao;
import cn.edu.bdu.mc.daos.impls.OrderDaoImpl;
import cn.edu.bdu.mc.services.OrderService;
import cn.edu.bdu.mc.services.impls.OrderServiceImpl;

/**
 * Servlet implementation class PayForServlet
 */
@WebServlet("/PayFor")
public class PayForServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PayForServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        try {
            String order_id = request.getParameter("order_id");
            OrderService orderService = new OrderServiceImpl();
            orderService.AfterPay(order_id);
            String htmlCode="<!DOCTYPE html>\n" + 
                    "<html>"
                    + "<head>"
                    + "<link rel=\"stylesheet\" href=\""+request.getContextPath()+"/bootstrap-3.3.7-dist/css/bootstrap.min.css\">"
                    + "</head>"
                    + "<body>"
                    + "<div style=\"position:absolute;left:44%;top:46%;height:100px;width:240px;background-color:rgba(145, 162, 196, 0.9);border:1px;text-align:center;\"id=\"quit1\">\r\n" + 
                    "   <h3>购买成功!</h3><a class=\"btn btn-info\" href=\""+request.getContextPath()+"/client/index.jsp\">继续购买</a>&nbsp;&nbsp;&nbsp;&nbsp;"
                            +"<a class=\"btn btn-info\" href=\""+request.getContextPath()+"/client/order.jsp\">查看订单</a>\n" + 
                    "</div>"
                    + "</body>"
                    + "</html>";
            response.getWriter().write(htmlCode);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

8.shouhuo.jsp

代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>收货地址</title>
</head>
<body style="background-color:#bbb;width:1400px;margin:0 auto">
<!-- 调用头部页面 -->
<div style="width:100%;height:100px;float:left">
<jsp:include page="/client/head.jsp"></jsp:include>
</div>
<!-- 通用内容体大小 -->
<div style="width:70%;height:720px;float:left;margin-left:15%;">
    <!-- 好看的图 -->
    <div style="width:55%;height:100%;float:left;margin-top:10%;">
        <img alt="快递员" src="${pageContext.request.contextPath }/client/img/kuaidi.jpg" style="width:90%;">
    </div>
    <!-- 登录界面 -->
    <div style="width:45%;height:80%;float:left;margin-top:7%">
        <h1 style="color:#8b6914;text-align:center">收货信息</h1>
        <hr style="height:2px;border:none;border-top:5px ridge green;" />
        <form action="${pageContext.request.contextPath }/ShouHuo" method="post" class="form-horizontal" role="form">
            <div class="form-group">
                <label for="lastname" class="col-sm-3 control-label input-lg">姓名</label>
                <div class="col-sm-9">
                    <input type="text" name="name" class="form-control input-lg"
                           placeholder="收货人姓名" style="float:left"/>
                </div>
            </div>
            <div class="form-group">
                <label for="firstname" class="col-sm-3 control-label input-lg">手机号</label>
                <div class="col-sm-9">
                    <input type="text" name="phone" 
                    class="form-control input-lg" placeholder="收货人手机号" style="float:left"/>
                </div>
            </div>
            
            <div class="form-group">
                <label for="firstname" class="col-sm-3 control-label input-lg">地址</label>
                <div class="col-sm-9">
                    <input type="text" name="address"
                    class="form-control input-lg" placeholder="收货人地址" style="float:left"/>
                </div>
            </div>
            <div class="form-group">
                <label for="firstname" class="col-sm-1 control-label input-lg"></label>
                <div class="col-sm-5">
                    <input type="submit" name="submit" value="提交"
                    class="form-control input-lg btn btn-primary"style="width:100%;float:left"/>
                </div>
                <div class="col-sm-5">
                    <input type="reset" name="reset" value="重置" id="re"
                    class="form-control input-lg btn btn-warning"style="width:100%;float:left"/>
                </div>
            </div>
        </form>
    </div>
</div>
<!-- 调用底部页面 -->
<div style="width:100%;height:60px;float:left">
<jsp:include page="/client/foot.jsp"></jsp:include>
</div>
</body>
</html>

效果图

9.order.jsp

代码

<%@page import="cn.edu.bdu.mc.beans.User"%>
<%@page import="cn.edu.bdu.mc.services.impls.OrderServiceImpl"%>
<%@page import="cn.edu.bdu.mc.services.OrderService"%>
<%@page import="cn.edu.bdu.mc.beans.Order"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<title>订单</title>
</head>
<%
    User user = (User)request.getSession().getAttribute("user");
    OrderService orderService = new OrderServiceImpl();
    List<Order>notPay = orderService.findNotPayByUser_id(user.getUser_id());
    List<Order>areadyPay = orderService.findAreadyPayByUser_id(user.getUser_id());
    
%>
<body style="background-color:#bbb;width:1400px;margin:0 auto">
<!-- 调用头部页面 -->
<div style="width:100%;height:100px;float:left">
<jsp:include page="/client/head.jsp"></jsp:include>
</div>
<!-- 通用内容体大小 -->
<div style="width:70%;height:720px;float:left;margin-left:15%;">
    未付款:<br>
    <% if(notPay==null){ %>
        无<br>
    <% }else{ %>
        <% for(Order order : notPay){%>
            id=<font><%=order.getOrder_id() %></font>&nbsp;&nbsp;money=<font><%=order.getMoney() %></font>&nbsp;&nbsp;
            <a href="${pageContext.request.contextPath }/PayFor?order_id=<%=order.getOrder_id() %>">付款</a>&nbsp;&nbsp;
            <a href="${pageContext.request.contextPath }/DelOrder?order_id=<%=order.getOrder_id() %>">删除</a>&nbsp;&nbsp;
            <br>
        <% } %>
    <% } %>
    已付款:<br>
    <% if(areadyPay==null){ %>
        无<br>
    <% }else{ %>
        <% for(Order order : areadyPay){%>
            id=<font><%=order.getOrder_id() %></font>&nbsp;&nbsp;money=<font><%=order.getMoney() %></font>&nbsp;&nbsp;
            <br>
        <% } %>
    <% } %>
</div>
<!-- 调用底部页面 -->
<div style="width:100%;height:60px;float:left">
<jsp:include page="/client/foot.jsp"></jsp:include>
</div>
</body>
</html>

效果图

点击付款后,还删除了一个,忘截图了

总结

今天弄得不是很多,又是各种报错。再加上开始的晚,于是拖到了现在才更。

posted @ 2019-06-23 00:55 return_false 阅读(...) 评论(...) 编辑 收藏