Realize the shopping cart implementation of the SSM simple mall project

Realize the shopping cart implementation of the SSM simple mall project

In this blog, we will use the SSM framework to implement a simple shopping cart function. We will use the Spring framework to manage beans, use the SpringMVC framework to process HTTP requests, and use the MyBatis framework to operate the database.
The idea of ​​realizing the shopping cart function of the SSM Simple Mall project is as follows:

  1. Create a database table: Create a product table and a shopping cart table. The product table is used to store product information, and the shopping cart table is used to store product information added to the shopping cart by the user.

  2. Create entity classes: Create product entity classes and shopping cart entity classes for mapping fields of database tables.

  3. Create DAO interfaces and Mapper files: Create product DAO interfaces and shopping cart DAO interfaces, and create corresponding Mapper files to define database operation methods.

  4. Create a Service interface and implementation class: Create a product Service interface and a shopping cart Service interface, and create corresponding implementation classes to process business logic.

  5. Create a Controller: Create a Product Controller and a Shopping Cart Controller to process user requests and return corresponding views.

  6. Create a JSP view: Create a JSP view of the product query page and shopping cart page to display product information and shopping cart content.

  7. Realize the shopping cart function: In the shopping cart Controller, realize the functions of adding items to the shopping cart and removing items from the shopping cart. Through the shopping cart Service and the shopping cart DAO, store the product information in the shopping cart table, and get the shopping cart content from the shopping cart table.

  8. Display the content of the shopping cart: In the JSP view of the shopping cart page, display the product information in the shopping cart through the shopping cart content returned by the shopping cart Controller, and provide the function of removing the product.

The above is the basic idea of ​​realizing the shopping cart function of the SSM Simple Mall project. Following this idea, you can gradually implement and expand the shopping cart functionality to meet project needs.

Step 1: Create a database table

First, we need to create a productdatabase table called , which is used to store information about products. The table structure is as follows:

CREATE TABLE product (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL,
  price DOUBLE NOT NULL,
  stock INT NOT NULL,
  category VARCHAR(100) NOT NULL
);

Step 2: Create Entity Classes

src/main/javaCreate a package named under the directory , com.example.entityand create a file named under the package Product.javaas the commodity entity class. code show as below:

package com.example.entity;

public class Product {
    
    
    private int id;
    private String name;
    private double price;
    private int stock;
    private String category;
    
    // 省略getter和setter方法
}

Step 3: Create a Mapper interface

src/main/javaCreate a package named under the directory , com.example.mapperand create a file named under the package ProductMapper.javaas the commodity Mapper interface. code show as below:

package com.example.mapper;

import com.example.entity.Product;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface ProductMapper {
    
    
    List<Product> getProductsByCategory(@Param("category") String category);
    
    Product getProductById(@Param("id") int id);
    
    void updateProduct(Product product);
}

Step 4: Create a Mapper mapping file

src/main/resourcesCreate a mapperfolder named under the directory, and create a file named under this folder as ProductMapper.xmlthe commodity Mapper mapping file. code show as below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.ProductMapper">
    <select id="getProductsByCategory" resultType="com.example.entity.Product">
        SELECT * FROM product WHERE category = #{category}
    </select>
    
    <select id="getProductById" resultType="com.example.entity.Product">
        SELECT * FROM product WHERE id = #{id}
    </select>
    
    <update id="updateProduct">
        UPDATE product SET stock = #{stock} WHERE id = #{id}
    </update>
</mapper>

Step 5: Create a Controller class

src/main/javaCreate a package named under the directory , and create a file named com.example.controllerunder the package as the commodity Controller class. ProductController.javacode show as below:

package com.example.controller;

import com.example.entity.Product;
import com.example.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class ProductController {
    
    
    @Autowired
    private ProductMapper productMapper;
    
    @GetMapping("/products")
    public String getProductsByCategory(@RequestParam("category") String category, Model model) {
    
    
        List<Product> products = productMapper.getProductsByCategory(category);
        model.addAttribute("products", products);
        return "products";
    }
    
    @GetMapping("/add-to-cart")
    public String addToCart(@RequestParam("productId") int productId, HttpServletRequest request) {
    
    
        Product product = productMapper.getProductById(productId);
        if (product != null) {
    
    
            List<Product> cart = (List<Product>) request.getSession().getAttribute("cart");
            if (cart == null) {
    
    
                cart = new ArrayList<>();
                request.getSession().setAttribute("cart", cart);
            }
            cart.add(product);
            
            // 更新商品库存
            product.setStock(product.getStock() - 1);
            productMapper.updateProduct(product);
        }
        
        return "redirect:/products?category=" + product.getCategory();
    }
    
    @GetMapping("/cart")
    public String viewCart(HttpServletRequest request, Model model) {
    
    
        List<Product> cart = (List<Product>) request.getSession().getAttribute("cart");
        model.addAttribute("cart", cart);
        return "cart";
    }
    
    @GetMapping("/remove-from-cart")
    public String removeFromCart(@RequestParam("productId") int productId, HttpServletRequest request) {
    
    
        List<Product> cart = (List<Product>) request.getSession().getAttribute("cart");
        if (cart != null) {
    
    
            Product productToRemove = null;
            for (Product product : cart) {
    
    
                if (product.getId() == productId) {
    
    
                    productToRemove = product;
                    break;
                }
            }
            if (productToRemove != null) {
    
    
                cart.remove(productToRemove);
                
                // 更新商品库存
                Product product = productMapper.getProductById(productId);
                product.setStock(product.getStock() + 1);
                productMapper.updateProduct(product);
            }
        }
        
        return "redirect:/cart";
    }
}

Step 6: Create a JSP view

src/main/webapp/WEB-INFCreate a viewsfolder named under the directory, and create a file named under the folder as products.jspthe JSP view of the product list. code show as below:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>商品列表</title>
</head>
<body>
    <h1>商品列表</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>名称</th>
            <th>价格</th>
            <th>库存</th>
            <th>分类</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td>${product.name}</td>
                <td>${product.price}</td>
                <td>${product.stock}</td>
                <td>${product.category}</td>
                <td>
                    <a href="/add-to-cart?productId=${product.id}">加入购物车</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

src/main/webapp/WEB-INF/viewsCreate a file named as the JSP view of the shopping cart in the directory cart.jsp. code show as below:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>购物车</title>
</head>
<body>
    <h1>购物车</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>名称</th>
            <th>价格</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${cart}" var="product">
            <tr>
                <td>${product.id}</td>
                <td>${product.name}</td>
                <td>${product.price}</td>
                <td>
                    <a href="/remove-from-cart?productId=${product.id}">移出购物车</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Step 7: Run the project

Now, we can start the project and access the product lookup page. Enter in the browser http://localhost:8080/products?category=电子产品to obtain and display eligible product information. Click the "Add to Cart" button and the item will be added to the shopping cart. On the shopping cart page http://localhost:8080/cart, you can check the items in the shopping cart and click the "Remove from shopping cart" button to remove the items from the shopping cart.

Guess you like

Origin blog.csdn.net/qq_22593423/article/details/132483092