package com.ryx.web.sy7;
import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;
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 java.io.IOException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
@WebServlet(name = "shoppingCart", value = "/shoppingCart")
public class CartController extends HttpServlet {
// 连接数据库
private static final String DB_URL = "jdbc:mysql://localhost:3306/test";
private static final String DB_USERNAME = "root";
private static final String DB_PASSWORD = "abc1234";
@SneakyThrows
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer id = Integer.valueOf(request.getParameter("id"));
String op = request.getParameter("op");
String whereCome = request.getHeader("Referer");
String redirectPath = null;
// 如果在主页点击加入购物车超链接,不跳转
if (whereCome.equals("http://localhost:8080/sy7/home.jsp")) {
redirectPath = request.getContextPath() + "/sy7/home.jsp";
} else {
// 如果在购物车页面增加或删除商品也不跳转
redirectPath = request.getContextPath() + "/sy7/cart.jsp";
}
HttpSession session = request.getSession();
Map<Integer, ProductVo> cart = (Map<Integer, ProductVo>) session.getAttribute("cart");
if (ObjectUtils.isEmpty(cart)) {
cart = new HashMap();
}
switch (op) {
// 添加商品
case "add":
if (!ObjectUtils.isEmpty(cart.get(id))) {
ProductVo productVo = cart.get(id);
productVo.setCount(productVo.getCount() + 1);
cart.put(id, productVo);
} else {
Class.forName("com.mysql.jdbc.Driver");
try (Connection conn = DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD)) {
String query = "SELECT * FROM product WHERE id = ?";
try (PreparedStatement stmt = conn.prepareStatement(query)) {
stmt.setInt(1, id);
try (ResultSet rs = stmt.executeQuery()) {
if (rs.next()) {
String name = rs.getString("name");
double price = rs.getDouble("price");
String imagePath = rs.getString("image_path");
Integer iid = rs.getInt("id");
ProductVo productVo = new ProductVo(iid, 1, name, price, imagePath);
cart.put(id, productVo);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
break;
// 减少商品
case "sub":
if (!ObjectUtils.isEmpty(cart.get(id))) {
ProductVo productVo = cart.get(id);
// 防止出现负数
if (productVo.getCount() > 1) {
productVo.setCount(productVo.getCount() - 1);
cart.put(id, productVo);
} else {
// 如果小于1则移除商品
cart.remove(id);
}
}
break;
}
session.setAttribute("cart", cart);
response.sendRedirect(redirectPath);
}
}
|