Java web MVC – Tạo trang giỏ hàng

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

Một trong những tính năng quan trọng của một trang web bán hàng đó là tính năng mua hàng. Khách hàng sau khi xem thông tin sản phẩm có thể đặt hàng trên website.

2. Thực thi

B1: 

Tạo servlet CartServlet kế thừa lớp BaseServlet đóng vai trò controller cho trang chi tiết sản phẩm

CartServlet có 2 phương thức doGet và doPost có vai trò xử lý 2 phương thức GET và POST của http

Với phương thức doGet chỉ sử dụng chức năng hiển thị thông tin giỏ hàng.

Với phương thức doPost xử lý các action create, update, delete giỏ hàng.

Chúng ta xây dựng các hàm riêng biệt cho các action để dễ quản lý code. Với cùng chỉ 1 phương thức nhưng xử lý 3 tình huống action khác nhau. Chúng ta cần một param action với 3 giá trị tương ứng:

create | update | delete

để phân biệt request http method post từ nguồn gởi tới cần action nào.

Ở đây chúng ta sẽ dùng session để thêm sản phẩm vào giỏ hàng

package binh.dev;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import binh.dev.data.model.OrderItem;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ACER NITRO
 */
public class CartServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        super.doGet(request, response);
        HttpSession session = request.getSession();
        List<OrderItem> cart = (List<OrderItem>) session.getAttribute("cart");
        if (cart == null) {
            cart = new ArrayList<>();
        }
//        ? thầy
        Logger.getLogger(CartServlet.class.getName()).log(Level.SEVERE, null, cart);
        request.setAttribute("cart", cart);
        session.setAttribute("total", total(cart));
        request.getRequestDispatcher("cart.jsp").include(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        switch (action) {
            case "create":
                createOrder(request);
                break;
            case "update":
                updateOrder(request);
                break;
            case "delete":
                deleteOrder(request);
                break;
            default:
                throw new AssertionError();
        }
        response.sendRedirect("CartServlet");
    }

    private void createOrder(HttpServletRequest request) {
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        int productId = Integer.parseInt(request.getParameter("productId"));
        double price = Double.parseDouble(request.getParameter("productPrice"));

        OrderItem orderItem = new OrderItem(quantity, price, 0, productId);
        HttpSession session = request.getSession();
        List<OrderItem> cart = (List<OrderItem>) session.getAttribute("cart");

        boolean isExistInCart = false;
        if (cart == null) {
            cart = new ArrayList<>();
        } else {
            for (OrderItem ord : cart) {
                if (ord.getProductId() == productId) {
                    ord.setQuantity(ord.getQuantity() + quantity);
                    isExistInCart = true;
                }
            }
        }

        if (!isExistInCart) {
            cart.add(orderItem);
        }
        session.setAttribute("cart", cart);
    }

    private void deleteOrder(HttpServletRequest request) {
        int productId = Integer.parseInt(request.getParameter("productId"));
        HttpSession session = request.getSession();
        List<OrderItem> cart = (List<OrderItem>) session.getAttribute("cart");

        if (cart != null) {
            for (int i = 0; i < cart.size(); i++) {
                OrderItem ord = cart.get(i);
                if (ord.getProductId() == productId) {
                    cart.remove(ord);
                }
            }
        }
        session.setAttribute("cart", cart);
    }

    private void updateOrder(HttpServletRequest request) {
        int productId = Integer.parseInt(request.getParameter("productId"));
        int quantity = Integer.parseInt(request.getParameter("quantity"));
        HttpSession session = request.getSession();
        List<OrderItem> cart = (List<OrderItem>) session.getAttribute("cart");

        if (cart != null && cart.isEmpty() == false) {
            for (OrderItem ord : cart) {
                if (ord.getProductId() == productId) {
                    ord.setQuantity(quantity);
                }
            }
        }
        session.setAttribute("cart", cart);
    }

    private int total(List<OrderItem> cart) {
        int sum = 0;
        for (OrderItem ods : cart) {
            sum += ods.getPrice() * ods.getQuantity();
        }
        return sum;
    }

}

B2: Tạo tập tin cart.jsp đổ dữ liệu từ session cart ra view

<%-- 
    Document   : home
    Created on : May 5, 2023, 7:19:37?PM
    Author     : binhdev
--%>
<%@include file="./inc/header.jsp"%>
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
<div id="wishlist-container">  
    <!-- PAGE HEADING -->
    <div class="page-heading">
        <div class="container">
            <div class="row">
                <h1 class="page-title"><i class="page-icon fa-regular fa-heart"></i> Wishlist Cart</h1>
            </div>
        </div>
    </div>
    <!-- sidebar -->
    <div class="sidebar-possition-without">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="xstore-wishlist-form">
                        <table class="xstore-wishlist-table">
                            <thead>
                                <tr>
                                    <th class="xstore-wishlist-checkbox">
                                        <input type="checkbox" name="product-bulk-select"
                                               id="wishlist-products-select">
                                    </th>
                                    <th class="xstore-wishlist-product">Product </th>
                                    <th class="xstore-wishlist-quality">Quanlity </th>
                                    <th class="xstore-wishlist-price">Unit Price </th>
                                    <th class="xstore-wishlist-stock_status">Amount Of Money </th>
                                    <th class="xstore-wishlist-action">Action </th>
                                </tr>
                            </thead>
                            <tbody class="xstore-wishlist-items">
                                <c:forEach items="${cart}" var="orderItem">
                                    <tr>
                                        <td class="xstore-wishlist-checkbox">
                                            <input type="checkbox" name="product-4069">
                                        </td>
                                        <td class="xstore-wishlist-product">
                                            <a href="" class="xstore-wishlist-product-link">
                                                <img src="${orderItem.product.thumbnail}" alt="loi"
                                                     class="xstore-wishlist-product-img">
                                            </a>
                                            <div class="xstore-wishlist-details">
                                                <a href="" class="xstore-wishlist-details-link">${orderItem.product.name} </a>
                                            </div>
                                        </td>
                                        <td class="xstore-wishlist-quality">
                                            <form action="CartServlet" method="post"  class="product-content-right-quality">
                                                <input type="hidden" name="action" value="update"/>
                                                <input type="hidden" name="productId" value="${orderItem.productId}"/>
                                                <input onchange="this.form.submit()" name="quantity" type="number" value="${orderItem.quantity}" min="1" class="quality-number quality-number-1"/>
                                            </form>
                                        </td>
                                        <td class="xstore-wishlist-price"><span
                                                class="product-price-1">
                                                <fmt:setLocale value = "en_US"/>
                                                <fmt:formatNumber type="currency" value = "${orderItem.product.price}" /> </span>
                                        </td>
                                        <td class="xstore-wishlist-stock_status">
                                            <p class="stock_status-step">
                                                <fmt:setLocale value = "en_US"/>
                                                <fmt:formatNumber type="currency" value = "${orderItem.product.price * orderItem.quantity}" /></p>
                                        </td>
                                        <td class="xstore-wishlist-action">
                                            <div class="action-wraper">
                                                <form action="CartServlet" method="post" class="action-wraper-list">
                                                    <input type="hidden" name="action" value="delete"/>
                                                    <input type="hidden" name="productId" value="${orderItem.productId}"/>
                                                    <button class="btn-cart" type="submit" value=""><i class="fa-solid fa-trash"></i></button>
                                                </form>
                                            </div>
                                            <span class="date-add">Added on: April 27, 2023 </span>
                                        </td>
                                    </tr>
                                </c:forEach>
                            </tbody>
                        </table>
                        <div class="form-action">
                            <div class="form-action-container">
                                <div class="form-action-left">
                                    <select class="form-action-select">
                                        <option value="add">Add to cart</option>
                                        <option value="Remove">Remove</option>
                                    </select>
                                    <div class="btn-select">Apply</div>
                                </div>
                                <div class="form-action-right">
                                    <div class="form-action-right-ask">
                                        <span class="right-ask-content"> Total:</span>
                                        <span class="right-ask-content">
                                            <fmt:setLocale value = "en_US"/>
                                            <fmt:formatNumber type="currency" value = "${total}" />
                                        </span>
                                    </div>
                                    <div class="form-action-right-btn"><a href="CheckoutServlet"
                                                                          class="form-action-right-link">Checkout All</a></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>
<%@include file="./inc/footer.jsp"%>