16 October 2016

Add To Cart - Session Shopping Cart - Giỏ Hàng JSP – Servlet - v2

http://localhost:8080/addToCart/ModelList.jsp
 http://localhost:8080/addToCart/ShoppingCart.jsp
ModelList.jsp
Java Web  2016
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title>Model List</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>

    <body>
        <center>
            <h2>Model List</h2>
            <a href="${pageContext.request.contextPath }/ShoppingCart.jsp" >View Cart</a>

            <table width="35%" border="1">
                <tr><td>
                        <form method="POST" action="CartController">
                            
                            Description:  Tech-Freaks imaginary model 1.<input type="hidden" name="description" value="Tech-Freaks imaginary model 1."><br/>
                            Quantity:<input type="number" name="quantity" value="1"><br/> 
                            Price: $10.00<input type="hidden" name="price" value="10"><br/>

                            <input type="submit" name="action" value="Add To Cart">
                            
                        </form>
                    </td>
                </tr>
            </table>

        </center>
    </body>
</html>
ShoppingCart.jsp
Java Web  2016
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
    <head>
        <title>Shopping Cart</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>

    <body>
        <center>
            <h2>Shopping Cart</h2>
            <a href="${pageContext.request.contextPath }/ModelList.jsp" >Model List</a> 
            <table width="75%" border="1">
                <tr bgcolor="#CCCCCC">
                    <td>Description</td>
                    <td>Quantity</td>
                    <td>Unit Price </td>
                    <td>Total</td>
                </tr>
                <jsp:useBean id="cart" scope="session" class="beans.CartBean" />

                <c:if test="${cart.lineItemCount == 0}">
                    <tr> <td colspan="4">- Cart is currently empty -</td></tr>
                </c:if>

                <c:forEach var="cartItem" items="${cart.list}" varStatus="counter">
                    <form name="item" method="POST" action="CartController">
                        <tr>
                            <td><c:out value="${cartItem.description}"/></td>
                            <td>
                                <input type='hidden' name='stt' value='<c:out value="${counter.count}"/>'>
                                <input type='number' name="quantity" value='<c:out value="${cartItem.quantity}"/>'> 
                                <input type="submit" name="action" value="Update">
                                <input type="submit" name="action" value="Delete">
                            </td>
                            <td>$<c:out value="${cartItem.price}"/></td>
                            <td>$<c:out value="${cartItem.totalCost}"/></td>
                        </tr>
                    </form>
                </c:forEach>
                <!--Total-->
                <tr>
                    <td colspan="3"> </td>
                    <td>Subtotal: $<c:out value="${cart.total}"/></td>
                </tr>
            </table>
        </center>
    </body>
</html>
Servlet: CartController.java
Java Web  2016
package servlet;

import beans.CartBean;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Lonely
 */
public class CartController extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String iAction = request.getParameter("action");

        if (iAction != null && !iAction.equals("")) {
            if (iAction.equals("Add To Cart")) {
                addToCart(request);
            } else if (iAction.equals("Update")) {
                updateCart(request);
            } else if (iAction.equals("Delete")) {
                deleteCart(request);
            }
        }
        response.sendRedirect("ShoppingCart.jsp");
    }

    protected void deleteCart(HttpServletRequest request) {
        HttpSession session = request.getSession();
        
        String iSTT = request.getParameter("stt");
        CartBean cartBean = null;

        Object iObject = session.getAttribute("cart");
        if (iObject != null) {
            cartBean = (CartBean) iObject;
        } else {
            cartBean = new CartBean();
        }
        cartBean.deleteCart(iSTT);
    }

    protected void updateCart(HttpServletRequest request) {
        HttpSession session = request.getSession();
        
        String iQuantity = request.getParameter("quantity");
        String iSTT = request.getParameter("stt");

        CartBean cartBean = null;

        Object objCartBean = session.getAttribute("cart");
        if (objCartBean != null) {
            cartBean = (CartBean) objCartBean;
        } else {
            cartBean = new CartBean();
        }
        cartBean.updateCart(iSTT, iQuantity);
    }

    protected void addToCart(HttpServletRequest request) {
        HttpSession session = request.getSession();
        
        String iDescription = request.getParameter("description");
        String iPrice = request.getParameter("price");
        String iQuantity = request.getParameter("quantity");

        CartBean cartBean = null;

        Object objCartBean = session.getAttribute("cart");

        if (objCartBean != null) {
            cartBean = (CartBean) objCartBean;
        } else {
            cartBean = new CartBean();
            session.setAttribute("cart", cartBean);
        }

        cartBean.addCart(iDescription, iPrice, iQuantity);
    }

}
CartBean.java
Java Web  2016
package beans;

import java.util.ArrayList;

/**
 *
 * @author Lonely
 */
public class CartBean {

    private ArrayList list = new ArrayList();
    private double total;

    public ArrayList getList() {
        return list;
    }

    public void setList(ArrayList list) {
        this.list = list;
    }

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public int getLineItemCount() {
        return list.size();
    }

    public void deleteCart(String stt) {
        int iSTT = 0;
        try {
            iSTT = Integer.parseInt(stt);
            list.remove(iSTT - 1);
            calculateOrderTotal();
        } catch (NumberFormatException nfe) {
            System.out.println("Error while deleting cart item: " + nfe.getMessage());
            nfe.printStackTrace();
        }
    }

    public void updateCart(String stt, String quantity) {
        int iSTT = Integer.parseInt(stt);
        CartItemBean cartItem = (CartItemBean) list.get(iSTT - 1);
        double iPrice = cartItem.getPrice();
        int iQuantity = Integer.parseInt(quantity);
        try {
            if (iQuantity > 0) {
                cartItem.setQuantity(iQuantity);
                cartItem.setTotalCost(iPrice * iQuantity);
                calculateOrderTotal();
            }
        } catch (NumberFormatException nfe) {
            System.out.println("Error while updating cart: " + nfe.getMessage());
            nfe.printStackTrace();
        }

    }

    public void addCart( String description, String price, String quantity) {
        double iPrice = Double.parseDouble(price);
        int iQuantity = Integer.parseInt(quantity);
        CartItemBean cartItem = new CartItemBean();
        try {
            if (iQuantity > 0) {
                
                cartItem.setDescription(description);
                cartItem.setPrice(iPrice);
                cartItem.setQuantity(iQuantity);
                cartItem.setTotalCost(iPrice * iQuantity);
                list.add(cartItem);
                calculateOrderTotal();
            }

        } catch (NumberFormatException nfe) {
            System.out.println("Error while parsing from String to primitive types: " + nfe.getMessage());
            nfe.printStackTrace();
        }
    }

    protected void calculateOrderTotal() {
        double plus = 0;
        for (int i = 0; i < list.size(); i++) {
            CartItemBean cartItem = (CartItemBean) list.get(i);
            plus += cartItem.getTotalCost();

        }
        setTotal(plus);
    }
}
CartItemBean.java
Java Web  2016
package beans;

/**
 *
 * @author Lonely
 */
public class CartItemBean {

    private String number;
    private String description;
    private double price;
    private int quantity;
    private double TotalCost;

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public double getTotalCost() {
        return TotalCost;
    }

    public void setTotalCost(double TotalCost) {
        this.TotalCost = TotalCost;
    }

}
web.xml
Java Web  2016
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>CartController</servlet-name>
        <servlet-class>servlet.CartController</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CartController</servlet-name>
        <url-pattern>/CartController</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
Download zip (import Netbeans)

2 nhận xét:

  1. a có thể giúp em phần tổng tiền đc ko ạ. em cảm ơn

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete

 

BACK TO TOP

Xuống cuối trang