Skip to content
This repository has been archived by the owner on May 11, 2024. It is now read-only.

Commit

Permalink
fix-cart
Browse files Browse the repository at this point in the history
  • Loading branch information
tamld590 committed Dec 2, 2023
1 parent bba42a0 commit 5a6b1cd
Show file tree
Hide file tree
Showing 10 changed files with 261 additions and 78 deletions.
7 changes: 1 addition & 6 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,7 @@
</properties>

<dependencies>
<dependency>
<groupId>com.bakaqc</groupId>
<artifactId>flower</artifactId>
<version>1.0.0</version>
<type>war</type>
</dependency>

<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
Expand Down
11 changes: 5 additions & 6 deletions src/main/java/com/bakaqc/flower/controller/CartController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import com.bakaqc.flower.service.Hash;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
Expand All @@ -16,12 +16,11 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String cartDataStr = getCookie(request);

String cartData = getCookie(request);

request.setAttribute("cart_data", cartData);

request.getRequestDispatcher("/view/cart.jsp").forward(request, response);
request.setAttribute("cart_data", cartDataStr);
RequestDispatcher rd = request.getRequestDispatcher("/view/cart.jsp");
rd.forward(request, response);
}

private static String getCookie(HttpServletRequest request) {
Expand Down
100 changes: 100 additions & 0 deletions src/main/java/com/bakaqc/flower/controller/CartCookieController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java to edit this template
*/
package com.bakaqc.flower.controller;

import com.bakaqc.flower.dao.ProductDAO;
import com.bakaqc.flower.model.Item;
import com.bakaqc.flower.model.Product;
import java.io.IOException;
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;

/**
*
* @author ACER
*/
@WebServlet(name = "CartCookieController", urlPatterns = {"/cookie"})
public class CartCookieController extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

String action = request.getParameter("action");
if (action == null) {
doGet_DisplayCart(request, response);
} else {
if (action.equalsIgnoreCase("buy")) {
doGet_Buy(request, response);
} else if (action.equalsIgnoreCase("remove")) {
doGet_Remove(request, response);
}
}

}



protected void doGet_DisplayCart(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/view/cart.jsp").forward(request, response);
}

protected void doGet_Remove(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
List<Item> cart = (List<Item>) session.getAttribute("cart");
int index = isExisting(request.getParameter("id"), cart);
cart.remove(index);
session.setAttribute("cart", cart);
response.sendRedirect("cart");
}

protected void doGet_Buy(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ProductDAO productDao = new ProductDAO();
HttpSession session = request.getSession();
if (session.getAttribute("cart") == null) {
List<Item> cart = new ArrayList<>();
cart.add(new Item((Product) productDao.getById(request.getParameter("id")), 1));
session.setAttribute("cart", cart);
} else {
List<Item> cart = (List<Item>) session.getAttribute("cart");
int index = isExisting(request.getParameter("id"), cart);
if (index == -1) {
cart.add(new Item((Product) productDao.getById(request.getParameter("id")), 1));
} else {
int quantity = cart.get(index).getQuantity() + 1;
cart.get(index).setQuantity(quantity);
}
session.setAttribute("cart", cart);
}
response.sendRedirect("cart");
}

private int isExisting(String id, List<Item> cart) {
for (int i = 0; i < cart.size(); i++) {
if (id.equals(cart.get(i).getProduct().getId())) {
return i;
}
}
return -1;
}

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

}

}
26 changes: 14 additions & 12 deletions src/main/java/com/bakaqc/flower/controller/ProductController.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*/
package com.bakaqc.flower.controller;

import com.bakaqc.flower.dao.ProductDAO;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
Expand All @@ -19,19 +20,20 @@ public class ProductController extends HttpServlet {

private static final long serialVersionUID = 1L;

public ProductController() {
super();
}
public ProductController() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* ProductModel productModel = new ProductModel();
request.setAttribute("products", productModel.findAll());
request.getRequestDispatcher("product/index.jsp").forward(request, response);
*/ }
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("product", ProductDAO.getInstance().selectAll());
request.getRequestDispatcher("view/product_detail.jsp").forward(request, response);
}

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

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import com.bakaqc.flower.dao.CategoriesDAO;
import com.bakaqc.flower.dao.ProductDAO;
import com.bakaqc.flower.model.Categories;
import com.bakaqc.flower.model.Item;
import com.bakaqc.flower.model.Product;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
Expand All @@ -18,10 +20,10 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
response.setContentType("text/html; charset=UTF-8");

String id = request.getParameter("pid");
String nameCAT = ProductDAO.getInstance().getNameCAT(id);

try {
Product p = ProductDAO.getInstance().getById(id);

String nameCAT = ProductDAO.getInstance().getNameCAT(id);
List<Categories> listCAT = CategoriesDAO.getInstance().selectAll();
List<Product> list = ProductDAO.getInstance().randomById(id, 4);

Expand All @@ -43,6 +45,24 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response)
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String productId = request.getParameter("id");
String quantity = request.getParameter("quantity");

if (productId != null && quantity != null) {
Product product = (Product) ProductDAO.getInstance().selectById(productId); // Phương thức giả định để lấy sản phẩm theo ID
if (product != null) {
Item newItem = new Item(product, Integer.parseInt(quantity));
List<Item> cart = (List<Item>) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList<>();
}
cart.add(newItem); // Thêm vào giỏ hàng
session.setAttribute("cart", cart); // Cập nhật lại session
}
}

response.sendRedirect("cart.jsp"); // Chuyển hướng người dùng đến trang giỏ hàng
}

}
4 changes: 2 additions & 2 deletions src/main/java/com/bakaqc/flower/dao/ProductDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public int countProduct() {
}

@Override
public List<Product> selectById(String id) {
public List<Product> selectById(String id) { //trả về 1 danh sách
List<Product> list = new ArrayList<>();
try {
Connection c = JDBC.getConnection();
Expand Down Expand Up @@ -106,7 +106,7 @@ public List<Product> selectById(String id) {
return list;
}

public Product getById(String id) {
public Product getById(String id) { //trả về 1 sản phẩm
List<Product> list = new ArrayList<>();
try {
Connection c = JDBC.getConnection();
Expand Down
7 changes: 6 additions & 1 deletion src/main/java/com/bakaqc/flower/model/Item.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ public class Item {
private int quantity;
private double price;

public Item(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}

public Item(Product product, int quantity, double price) {
this.product = product;
this.quantity = quantity;
Expand Down Expand Up @@ -36,4 +41,4 @@ public void setPrice(double price) {
this.price = price;
}

}
}
53 changes: 52 additions & 1 deletion src/main/webapp/js/cartHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ const tooltips = document.querySelectorAll(".product");

for (let price of prices) {
const amount = parseFloat(price.textContent);

price.textContent = formatCurrencyVND(amount);
}

Expand All @@ -19,3 +18,55 @@ function formatCurrencyVND(amount) {
tooltips.forEach(t => {
new bootstrap.Tooltip(t);
});
// Hàm để cập nhật giỏ hàng hoặc thêm sản phẩm vào giỏ hàng
function updateCart() {
var productId = '<%=pro.id%>'; // Lấy ID sản phẩm từ URL (giả sử sản phẩm truyền qua param "id")
var productName = '<%=pro.name%>'; // Lấy tên sản phẩm
var productPrice = '<%=pro.price%>'; // Lấy giá sản phẩm
var productQuantity = 1; // Số lượng sản phẩm mặc định khi thêm vào giỏ hàng
var cart = getCookie("cart");
if (cart !== "") {
// Nếu cookie "cart" đã tồn tại, cập nhật giỏ hàng
var cartItems = JSON.parse(cart);
if (cartItems.hasOwnProperty(productId)) {
// Nếu sản phẩm đã tồn tại trong giỏ hàng, tăng số lượng
cartItems[productId] += productQuantity;
} else {
// Nếu sản phẩm chưa có trong giỏ hàng, thêm sản phẩm vào giỏ hàng với số lượng là 1
cartItems[productId] = productQuantity;
}
// Cập nhật cookie "cart" với giỏ hàng mới
setCookie("cart", JSON.stringify(cartItems), 30); // 30 là số ngày cookie sẽ tồn tại
} else {
// Nếu cookie "cart" chưa tồn tại, tạo mới cookie và lưu ID sản phẩm vào đó với số lượng là 1
var newCart = {};
newCart[productId] = productQuantity;
setCookie("cart", JSON.stringify(newCart), 30); // 30 là số ngày cookie sẽ tồn tại
}
}

// Hàm để lấy giá trị của một cookie
function getCookie(name) {
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name + '=') === 0) {
return c.substring(name.length + 1, c.length);
}
}
return "";
}

// Hàm để thiết lập giá trị cho một cookie
function setCookie(name, value, days) {
var d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

updateCart(); // Gọi hàm cập nhật giỏ hàng hoặc thêm sản phẩm vào giỏ hàng khi trang được tải
Loading

0 comments on commit 5a6b1cd

Please sign in to comment.