项目简介

智慧商城(Smart Mall)是一个基于 Spring Boot 3.2 + Vue 3 + Redis + MySQL + Nginx 构建的现代化电商平台。该项目采用前后端分离架构,完整实现了用户购物、商品管理、订单处理等核心电商功能,是学习企业级 Java 全栈开发的优秀参考案例。

技术栈详解

后端技术栈

技术 版本 职责
Spring Boot 3.2.x 应用框架
MySQL 8.0+ 关系型数据库
Redis 7.0+ 缓存服务
MyBatis Plus 3.5.x ORM框架
Spring Security 6.x 安全框架
JWT 0.12.x 身份认证
Maven 3.x 构建工具

前端技术栈

技术 版本 职责
Vue 3.4.x 前端框架
Vite 5.x 构建工具
Ant Design Vue 4.2.x UI组件库
Pinia 3.x 状态管理
Vue Router 4.x 路由管理
Axios 1.x HTTP客户端
Tailwind CSS 3.x CSS框架
TypeScript 5.4 类型安全

核心功能模块

用户端功能

  1. 用户认证 - 注册/登录,基于 JWT 的无状态认证机制
  2. 商品浏览 - 分类筛选、关键词搜索、分页展示
  3. 购物车管理 - 添加商品、修改数量、删除商品
  4. 订单管理 - 创建订单、查看订单列表、订单详情
  5. 地址管理 - 收货地址增删改查
  6. 个人中心 - 用户信息查看与修改

管理端功能

  1. 商品管理 - 商品的增删改查
  2. 订单管理 - 订单状态更新(待付款、已付款、已发货、已完成)
  3. 数据仪表盘 - 销售数据可视化展示

架构设计

项目结构

SmartMall/
├── backend/                    # 后端代码
│   ├── src/main/java/com/example/smartmall/
│   │   ├── controller/        # REST API控制器层
│   │   ├── service/           # 业务逻辑层
│   │   │   └── impl/          # 服务实现类
│   │   ├── mapper/            # 数据访问层
│   │   ├── entity/            # 数据库实体
│   │   ├── dto/               # 数据传输对象
│   │   ├── config/            # 配置类
│   │   ├── filter/            # 过滤器
│   │   └── utils/             # 工具类
│   └── src/main/resources/
│       ├── application.yml    # 应用配置
│       ├── schema.sql         # 数据库初始化脚本
│       └── data.sql           # 初始数据
│
├── frontend/                   # 前端代码
│   ├── src/
│   │   ├── components/        # 公共组件
│   │   ├── pages/             # 页面组件
│   │   │   └── admin/         # 管理员页面
│   │   ├── stores/            # Pinia状态管理
│   │   ├── api/               # API请求封装
│   │   ├── types/             # TypeScript类型定义
│   │   └── router/            # 路由配置
│   └── dist/                  # 构建产物
│
├── nginx/                     # Nginx配置
└── docker-compose.yml         # Docker编排

关键设计亮点

1. JWT 认证机制

后端通过自定义 JwtAuthenticationFilter 实现 Token 验证:

// SecurityConfig.java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .csrf(AbstractHttpConfigurer::disable)
        .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(auth -> auth.requestMatchers("/**").permitAll())
        .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

前端通过 Axios 拦截器自动携带 Token:

// api/index.ts
api.interceptors.request.use((config) => {
    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }
    return config
})
2. 购物车服务实现

购物车服务采用数据库存储方案,支持同商品数量累加:

// CartServiceImpl.java
public CartItem addToCart(Long userId, CartItemRequest request) {
    CartItem existingItem = cartItemMapper.selectOne(new LambdaQueryWrapper<CartItem>()
            .eq(CartItem::getUserId, userId)
            .eq(CartItem::getProductId, request.getProductId()));

    if (existingItem != null) {
        existingItem.setQuantity(existingItem.getQuantity() + request.getQuantity());
        cartItemMapper.updateById(existingItem);
        return existingItem;
    }
    // 创建新购物车项...
}
3. 订单创建事务处理

订单创建涉及多表操作,使用 @Transactional 保证数据一致性:

// OrderServiceImpl.java
@Transactional
public Order createOrder(Long userId, CreateOrderRequest request) {
    // 1. 验证购物车不为空
    // 2. 验证收货地址
    // 3. 生成订单号
    // 4. 计算总价并扣减库存
    // 5. 创建订单和订单明细
    // 6. 清空购物车
}
4. Docker 容器化部署

项目提供完整的 docker-compose.yml,一键启动所有服务:

services:
  mysql:    # 数据库
  redis:    # 缓存
  backend:  # 后端服务
  nginx:    # 反向代理

核心代码解读

后端控制器示例

[ProductController.java]展示了标准的 REST API 设计:

@RestController
@RequestMapping("/api/products")
@RequiredArgsConstructor
public class ProductController {
    private final ProductService productService;

    @GetMapping
    public Response<Page<Product>> getProducts(
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Product> products = productService.getProducts(categoryId, keyword, page, size);
        return Response.success(products);
    }
}

前端状态管理

[user.ts]使用 Pinia 管理用户状态:

export const useUserStore = defineStore('user', () => {
    const user = ref<User | null>(null)
    const token = ref(localStorage.getItem('token') || '')

    const login = async (username: string, password: string) => {
        const response = await apiPost<{ token: string }>('/auth/login', { username, password })
        token.value = response.data.token
        localStorage.setItem('token', token.value)
        await fetchUser()
    }

    return { user, token, login, logout, isAdmin }
})

前端页面示例

[HomePage.vue]展示了商品分类和热门商品展示:

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import api from '@/api'
import type { Product, Category } from '@/types'
import Carousel from '@/components/Carousel.vue'
import ProductCard from '@/components/ProductCard.vue'

const products = ref<Product[]>([])
const categories = ref<Category[]>([])

onMounted(async () => {
    const productResponse = await api.get('/products', { params: { page: 1, size: 8 } })
    products.value = productResponse.data.records
    const categoryResponse = await api.get('/categories')
    categories.value = categoryResponse.data
})
</script>

快速开始

环境要求

  • JDK 21+
  • Node.js 20+
  • MySQL 8.0+
  • Redis 7.0+

启动步骤

1. 数据库配置

CREATE DATABASE smart_mall CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

2. 启动后端服务

cd backend
mvn spring-boot:run
# 服务启动在 http://localhost:8080

3. 启动前端服务

cd frontend
npm install
npm run dev
# 服务启动在 http://localhost:5173

4. Docker 一键部署

docker-compose up -d

默认账号

用户名 密码 角色
admin 123456 管理员
user 123456 普通用户

API 接口一览

模块 接口 方法 描述
认证 /api/auth/login POST 用户登录
认证 /api/auth/register POST 用户注册
用户 /api/users/me GET 获取当前用户
商品 /api/products GET 获取商品列表
商品 /api/products/:id GET 获取商品详情
购物车 /api/cart GET 获取购物车
购物车 /api/cart POST 添加商品
订单 /api/orders GET 获取订单列表
订单 /api/orders POST 创建订单
管理员 /api/admin/products POST 创建商品
管理员 /api/admin/orders/:id/status PUT 更新订单状态

技术亮点总结

  1. 无状态认证 - 基于 JWT 的 Token 认证,服务端无需维护会话状态
  2. 事务一致性 - 订单创建使用 @Transactional 保证数据完整性
  3. 类型安全 - 前端使用 TypeScript,后端使用强类型语言
  4. 组件化开发 - Vue 3 Composition API + 组件复用
  5. 容器化部署 - Docker Compose 一键部署所有服务
  6. RESTful 设计 - 标准的 REST API 接口规范

总结

智慧商城项目展示了一个完整的现代化电商平台开发流程,涵盖了从需求分析、架构设计到代码实现的全过程。无论是学习 Spring Boot 后端开发,还是 Vue 3 前端开发,这个项目都是一个很好的实践案例。

项目代码结构清晰,遵循了业界最佳实践,可以作为企业级电商系统开发的参考模板。如果您对某个模块有更深的兴趣,欢迎深入研究源码进行学习!

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐