Java web MVC – Admin-CRUD đơn hàng

1. Phân tích chức năng

Xây dựng chức năng:

  • Hiển thị
  • Thêm
  • Sửa
  • Xoá

dữ liệu bảng đơn hàng (orders)

2. Thực thi

2.1. Chức năng hiển thị

B1: Tạo controller IndexOrderServlet kế thừa lớp BaseAdminServlet thực hiện chức năng quản lý trang hiển thị dữ liệu các đơn hàng

package binh.dev.admin.order;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import binh.dev.BaseServlet;
import binh.dev.data.dao.DatabaseDao;
import binh.dev.data.dao.OrderDao;
import binh.dev.data.model.Order;

/**
 *
 * @author binhdev
 */
public class IndexOrderServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            OrderDao orderDao = DatabaseDao.getInstance().getOrderDao();
            // Tìm xong đưa vào 1 list <order>
            List<Order> orderList = orderDao.findAll();
            
            // set dữ liệu lên 
            request.setAttribute("orderList", orderList);
            request.getRequestDispatcher("admin/order/index.jsp").include(request, response);
            
    }

   
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }
}

B2: Tạo giao diện index.jsp trong thư mục web/admin/orders làm chức năng view

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">

      <head>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>CornSalad Admin - Dashboard</title>

        <!-- Custom fonts for this template-->
        <link href="./assets/admin/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
        <link
            href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
            rel="stylesheet">

        <!-- Custom styles for this template-->
        <link href="./assets/admin/css/sb-admin-2.min.css" rel="stylesheet">

    </head>

    <body id="page-top">

        <!-- Page Wrapper -->
        <div id="wrapper">

            <!-- Sidebar -->
            <%@include file="../inc/sidebar.jsp" %>
            <!-- End of Sidebar -->

            <!-- Content Wrapper -->
            <div id="content-wrapper" class="d-flex flex-column">

                <!-- Main Content -->
                 <!-- Topbar -->
                    <%@include file="../inc/header.jsp" %>
                    <!-- End of Topbar -->
                <!-- Begin Page Content -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                    <h1 class="h3 mb-2 text-gray-800">Order</h1>
                    <p class="mb-4">Danh sách các đơn hàng</p>

                    <!-- DataTales Example -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">DataTables Example</h6>
                        </div>
                        <div class="card-body">

                            <div class="table-responsive">
                                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>STT</th>
                                            <th>Code</th>
                                            <th>Status</th>
                                            <th>Email</th>
                                            <th>#</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <c:set var="index" value="0"/>
                                        <c:forEach items="${orderList}" var="order">
                                        <c:set var="index" value="${index + 1}"/>
                                            <tr >
                                                <td>${index}</td>
                                                <td> <a href="OrderItemServlet?orderId=${order.id}">${order.code}</td>
                                                <td>${order.status}</td>
                                                <td>${order.user.email}</td>
                                                <td>
                                                    <a href="EditOrderServlet?orderId=${order.id}">Edit</a>
                                                </td>
                                                
                                            </tr>
                                        </c:forEach>
                                    </tbody>
                                </table>
                            </div>

                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->
                <!-- End of Main Content -->

                <!-- Footer -->
                <%@include file="../inc/footer.jsp" %>
                <!-- End of Footer -->

            </div>
            <!-- End of Content Wrapper -->

        </div>
        <!-- End of Page Wrapper -->

        <!-- Scroll to Top Button-->
        <a class="scroll-to-top rounded" href="#page-top">
            <i class="fas fa-angle-up"></i>
        </a>



        <!-- Bootstrap core JavaScript-->
        <script src="./assets/admin/vendor/jquery/jquery.min.js"></script>
        <script src="./assets/admin/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

        <!-- Core plugin JavaScript-->
        <script src="./assets/admin/vendor/jquery-easing/jquery.easing.min.js"></script>

        <!-- Custom scripts for all pages-->
        <script src="./assets/admin/js/sb-admin-2.min.js"></script>

        <!-- Page level plugins -->
        <script src="./assets/admin/vendor/chart.js/Chart.min.js"></script>

        <!-- Page level custom scripts -->
        <script src="./assets/admin/js/demo/chart-area-demo.js"></script>
        <script src="./assets/admin/js/demo/chart-pie-demo.js"></script>

    </body>

</html>

2.2. Chức năng thêm mới

Đơn hàng thêm mới từ việc mua hàng của khách hàng. Ở đây chúng ta đang xây dựng phía quản lý ở admin. Không có chức năng mua hàng ở đây.

2.3. Chức năng cập nhật

B1: Tạo controller UpdateOrderServlet kế thừa lớp BaseAdminServlet thực hiện chức năng cập nhật đơn hàng

package binh.dev.admin.order;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import binh.dev.BaseServlet;
import binh.dev.data.dao.DatabaseDao;
import binh.dev.data.dao.OrderDao;
import binh.dev.data.model.Order;

/**
 *
 * @author binhdev
 */
public class EditOrderServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        OrderDao orderDao = DatabaseDao.getInstance().getOrderDao();
        int orderId = Integer.parseInt(request.getParameter("orderId"));
        Order order = orderDao.find(orderId);

        session.setAttribute("order", order);
        request.getRequestDispatcher("admin/order/edit.jsp").include(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        OrderDao orderDao = DatabaseDao.getInstance().getOrderDao();

        int orderId = Integer.parseInt(request.getParameter("orderId"));

        Order order = orderDao.find(orderId);

        String code = request.getParameter("code");
        String status = request.getParameter("status");

        order.setCode(code);

        order.setStatus(status);

        if (code.isEmpty() || status.isEmpty()) {
            session.setAttribute("errorMessage", "Vui lòng điền đầy đủ thông tin");
            request.getRequestDispatcher("admin/order/edit.jsp").forward(request, response);
        }
        else{
            orderDao.update(order);
            response.sendRedirect("IndexOrderServlet");
        }
            
        }

    }

B2: Tạo tập tin update.jsp trong thư mục web/admin/orders làm chức năng view

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">

    <head>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>CornSalad Admin - Dashboard</title>

        <!-- Custom fonts for this template-->
        <link href="./assets/admin/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
        <link
            href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
            rel="stylesheet">

        <!-- Custom styles for this template-->
        <link href="./assets/admin/css/sb-admin-2.min.css" rel="stylesheet">
        <link href="./assets/admin/css/style.css" rel="stylesheet">
    </head>

    <body id="page-top">

        <!-- Page Wrapper -->
        <div id="wrapper">

            <!-- Sidebar -->
            <%@include file="../inc/sidebar.jsp" %>
            <!-- End of Sidebar -->

            <!-- Content Wrapper -->
            <div id="content-wrapper" class="d-flex flex-column">
                <!-- Topbar -->
                <%@include file="../inc/header.jsp" %>
                <!-- End of Topbar -->
                <!-- Main Content -->
                <div class="container-fluid">
                    <form action="EditOrderServlet" method="post">
                        <input type="hidden" name="orderId" value="${order.id}">
                        <div class="form-group">
                            <label for="exampleInputEmail1">Code</label>
                            <input type="text" name="code"  class="form-control" placeholder="Enter Code" value="${order.code}">
                        </div>
                        <div class="form-group">
                            <label for="exampleInputEmail1">Status</label>
                            <select name="status" class="form-control">
                                <option value="pending" <c:if test="${order.status == 'pending'}">selected</c:if>>Pending</option>
                                <option value="finished" <c:if test="${order.status == 'finished'}">selected</c:if>>Finished</option>
                                </select>
                            </div>
                            <div class="form-text text-muted" >
                            ${errorMessage}
                            <c:remove var="errorMessage" scope="session" />
                        </div>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
                <!-- End of Main Content -->

                <!-- Footer -->
                <%@include file="../inc/footer.jsp" %>
                <!-- End of Footer -->

            </div>
            <!-- End of Content Wrapper -->

        </div>
        <!-- End of Page Wrapper -->

        <!-- Scroll to Top Button-->
        <a class="scroll-to-top rounded" href="#page-top">
            <i class="fas fa-angle-up"></i>
        </a>



        <!-- Bootstrap core JavaScript-->
        <script src="./assets/admin/vendor/jquery/jquery.min.js"></script>
        <script src="./assets/admin/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

        <!-- Core plugin JavaScript-->
        <script src="./assets/admin/vendor/jquery-easing/jquery.easing.min.js"></script>

        <!-- Custom scripts for all pages-->
        <script src="./assets/admin/js/sb-admin-2.min.js"></script>

        <!-- Page level plugins -->
        <script src="./assets/admin/vendor/chart.js/Chart.min.js"></script>

        <!-- Page level custom scripts -->
        <script src="./assets/admin/js/demo/chart-area-demo.js"></script>
        <script src="./assets/admin/js/demo/chart-pie-demo.js"></script>

    </body>

</html>

2.3. Chức năng xoá

Đơn hàng chỉ thay đổi trạng thái hoặc soft delete không nên xoá vĩnh viễn vì sẽ ảnh hưởng thống kê về sau không thể truy vết