JavaWeb World (11): diseño e implementación del carrito de compras

Resumen del carrito de compras

Diseño de carrito de compras

  1. Sobre la base de Sesión Cesta
    carro de compras se almacena en el ámbito de sesión, se cierra el navegador, no hay compra
  2. Sobre la base de la galleta de la compra 's
    -basado sesión, como el contenido de la presencia del navegador, la información no pueden ser compartidos a través de diferentes ordenadores
  3. Carrito de compras basado en la base de datos Cookie +
    Si no ha iniciado sesión cuando compra el producto, lo almacenará temporalmente en la cookie.
    Si ha iniciado sesión, lea primero los datos en la cookie y luego guárdelos en la base de datos (puede ver la información en la base de datos en cualquier lugar )

Modelo de carrito de compras y creación de objetos

El proceso es aproximadamente el siguiente:
Proceso de carrito de compras

CartItem.java :

//购物车中的商品对象
@Data
public class CartItem {
	private String id;
	private String name;//商品名称
	private BigDecimal price;//单价
	private Integer num;//购买数量
}

ShoppingCart.java :

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

//购物车对象
public class ShoppingCart {
	//购物车中的多个商品对象
	private List<CartItem> items = new ArrayList<>();
	//购物车总价
	private BigDecimal totalPrice;

	//把商品添加进购物车
	public void save(CartItem newItem) {
		for (CartItem item : items) {
			//如果该商品已经在购物车里,则增加数量
			if (item.getId().equals(newItem.getId())) {
				item.setNum(item.getNum() + newItem.getNum());
				return;
			}
		}
		items.add(newItem);
	}

	//从购物车中移除指定id的商品
	public void delete(String id) {
		Iterator<CartItem> it = items.iterator();
		while (it.hasNext()) {
			CartItem item = it.next();
			if (item.getId().equals(id)) {
				//items.remove(item);//错误,防止并发修改
				it.remove();
				break;
			}
		}
	}

	//购物车中所有的商品
	public List<CartItem> getItem() {
		return items;
	}

	//购物车总价
	public BigDecimal getTotalPrice() {
		BigDecimal totalPrice = BigDecimal.ZERO;
		for (CartItem item : items) {
			totalPrice = totalPrice.add(item.getPrice().multiply(new BigDecimal(item.getNum())));
		}
		return totalPrice;
	}
}

La realización del carrito de compras.

Primero escriba una solicitud de Servlet:

ShoppingCartServlet.java :

import java.io.IOException;
import java.math.BigDecimal;

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 com.cherry._02_shoppingcart.domain.CartItem;
import com.cherry._02_shoppingcart.domain.ShoppingCart;

//处理购物车的添加删除操作
@WebServlet("/shoppingcart")
public class ShoppingCartServlet extends HttpServlet {

	private static final long serialVersionUID = -5568788051811437779L;

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String cmd = req.getParameter("cmd");
		if ("save".equals(cmd)) {
			this.save(req, resp);
		} else if ("delete".equals(cmd)) {
			this.delete(req, resp);
		}
		resp.sendRedirect("/shoppingcart/cart_list.jsp");
	}

	protected void save(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.接收请求参数
		String name = req.getParameter("name");
		String num = req.getParameter("num");
		String id = "";
		BigDecimal price = BigDecimal.ZERO;
		//写死了编号和单价
		if ("iPhone 11".equals(name)) {
			id = "11";
			price = new BigDecimal("5000");
		} else if ("iPhone 11 Pro".equals(name)) {
			id = "22";
			price = new BigDecimal("8000");
		} else if ("iPhone 11 Pro Max".equals(name)) {
			id = "33";
			price = new BigDecimal("11000");
		}
		CartItem item = new CartItem(id, name, price, Integer.valueOf(num));

		//2.调用业务方法
		ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("SHOPPINGCART_IN_SESSION");
		System.out.println(cart);
		if (cart == null) {
			cart = new ShoppingCart();
			req.getSession().setAttribute("SHOPPINGCART_IN_SESSION", cart);
		}
		cart.save(item);
		System.out.println(cart);

		//3.控制界面跳转
	}

	protected void delete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.接收请求参数
		String id = req.getParameter("id");
		//2.调用业务方法
		ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("SHOPPINGCART_IN_SESSION");
		cart.delete(id);
		//3.控制界面跳转
	}
}

En aras de la simplicidad, el precio unitario y el número de serie del producto se escriben primero, de hecho, debe obtenerse a través de la base de datos.
Luego escriba una página JSP:

cart_list.jsp :

package com.cherry._02_shoppingcart.servlet;

import java.io.IOException;
import java.math.BigDecimal;

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 com.cherry._02_shoppingcart.domain.CartItem;
import com.cherry._02_shoppingcart.domain.ShoppingCart;

//处理购物车的添加删除操作
@WebServlet("/shoppingcart")
public class ShoppingCartServlet extends HttpServlet {

	private static final long serialVersionUID = -5568788051811437779L;

	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String cmd = req.getParameter("cmd");
		if ("save".equals(cmd)) {
			this.save(req, resp);
		} else if ("delete".equals(cmd)) {
			this.delete(req, resp);
		}
		resp.sendRedirect("/shoppingcart/cart_list.jsp");
	}

	protected void save(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.接收请求参数
		String name = req.getParameter("name");
		String num = req.getParameter("num");
		String id = "";
		BigDecimal price = BigDecimal.ZERO;
		if ("iPhone 11".equals(name)) {
			id = "11";
			price = new BigDecimal("5000");
		} else if ("iPhone 11 Pro".equals(name)) {
			id = "22";
			price = new BigDecimal("8000");
		} else if ("iPhone 11 Pro Max".equals(name)) {
			id = "33";
			price = new BigDecimal("11000");
		}
		CartItem item = new CartItem(id, name, price, Integer.valueOf(num));

		//2.调用业务方法
		ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("SHOPPINGCART_IN_SESSION");
		System.out.println(cart);
		if (cart == null) {
			cart = new ShoppingCart();
			req.getSession().setAttribute("SHOPPINGCART_IN_SESSION", cart);
		}
		cart.save(item);
		System.out.println(cart);

		//3.控制界面跳转
	}

	protected void delete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//1.接收请求参数
		String id = req.getParameter("id");
		//2.调用业务方法
		ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("SHOPPINGCART_IN_SESSION");
		cart.delete(id);
		//3.控制界面跳转
	}
}

product_list.jsp :

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="/shoppingcart?cmd=save" method="POST">
		商品名称:
			<select name="name">
				<option>iPhone 11</option>
				<option>iPhone 11 Pro</option>
				<option>iPhone 11 Pro Max</option>			
			</select></br>
		购买数量:<input type="number" name="num" min="1"}/>
		<br/><input type="submit" value="添加进购物车"/>
	</form>
</body>
</html>

Cuando JSP obtiene las propiedades del objeto de alcance, se llama al método getter r de manera predeterminada , por lo tanto, use el complemento lombok para generar el Getter Setter o escríbalo usted mismo, pero debe ser que getXxxx (nombre de propiedad) no se puede escribir incorrectamente , de lo contrario, informará una excepción de que la propiedad no se puede encontrar . Estoy escribiendo el método get de elementos para getItem durante mucho tiempo, y debería escribirse como getItems .

Aunque el resultado final es feo, las funciones básicas se pueden lograr:
1
2

56 artículos originales publicados · Me gusta 23 · Visitas 20,000+

Supongo que te gusta

Origin blog.csdn.net/qq_42650988/article/details/104107607
Recomendado
Clasificación