SSM+Vue农产品电商系统开发实战
1. 项目背景与核心价值
最近在整理毕设资料时,翻出了去年帮学弟做的农产品销售管理系统。这个基于SSM+Vue的全栈项目,不仅顺利通过了答辩,还被当地一家农业合作社采用作为实际运营系统。今天就把这个项目的完整实现思路和关键代码分享给大家,特别适合正在做电商类毕设的同学参考。
传统农产品销售面临几个痛点:一是线下交易效率低,二是供需信息不对称,三是缺乏数字化管理手段。我们这个系统正是为了解决这些问题而设计,主要实现了商品展示、在线交易、订单管理、数据分析等核心功能模块。采用前后端分离架构,后端使用Spring+SpringMVC+MyBatis框架组合,前端基于Vue+ElementUI,数据库选用MySQL 8.0。
提示:这个项目完整代码约1.2万行,包含35个Java类、28个Vue组件。建议先理解整体架构再查看具体实现。
2. 系统架构设计
2.1 技术栈选型分析
选择SSM框架组合主要基于以下考虑:
- Spring的IoC容器管理业务对象,解决依赖注入问题
- SpringMVC的拦截器非常适合做权限验证
- MyBatis的动态SQL能灵活应对农产品多条件查询
- Vue的响应式特性完美匹配商品数据实时更新需求
- ElementUI的表格和表单组件大幅提升开发效率
系统采用经典的三层架构:
表示层:Vue + ElementUI + Axios
业务层:Spring + SpringMVC
数据层:MyBatis + MySQL + Redis缓存
2.2 数据库设计要点
农产品销售系统的ER图包含12个核心表,这里重点说明几个关键表设计:
- 商品表(product)
CREATE TABLE `product` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL COMMENT '商品名称',
`category_id` int NOT NULL COMMENT '分类ID',
`price` decimal(10,2) NOT NULL COMMENT '销售价',
`origin_price` decimal(10,2) DEFAULT NULL COMMENT '原价',
`stock` int NOT NULL DEFAULT '0' COMMENT '库存',
`sold_num` int DEFAULT '0' COMMENT '已售数量',
`images` text COMMENT '图片JSON数组',
`detail` text COMMENT '商品详情',
`status` tinyint DEFAULT '1' COMMENT '状态:1-上架 0-下架',
`farm_id` int DEFAULT NULL COMMENT '关联农场ID',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_category` (`category_id`),
KEY `idx_farm` (`farm_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
- 订单表(order)的特殊处理
- 使用order_no作为业务主键(雪花算法生成)
- 包含订单状态流转记录字段
- 设计冗余字段减少关联查询
注意:农产品订单需要特别处理时效性,我们额外设计了order_expire_time字段来自动取消未支付订单。
3. 核心功能实现
3.1 商品展示模块
前端采用Vue的虚拟滚动技术优化长列表性能:
<template>
<el-table
:data="products"
height="600"
row-key="id"
@row-click="handleRowClick">
<el-table-column prop="name" label="商品名称" width="180" />
<el-table-column prop="price" label="价格" width="100">
<template #default="{row}">
<span class="price">¥{{ row.price.toFixed(2) }}</span>
<span v-if="row.origin_price" class="origin-price">
¥{{ row.origin_price.toFixed(2) }}
</span>
</template>
</el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
products: [] // 通过axios从后端获取
}
},
methods: {
async loadProducts() {
const res = await this.$http.get('/api/product/list', {
params: {
page: 1,
size: 50,
categoryId: this.activeCategory
}
})
this.products = res.data.items
}
}
}
</script>
后端商品查询接口的关键实现:
@RestController
@RequestMapping("/api/product")
public class ProductController {
@Autowired
private ProductService productService;
@GetMapping("/list")
public Result list(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size,
@RequestParam(required = false) Integer categoryId,
@RequestParam(required = false) String keyword) {
// 构建查询条件
ProductQuery query = new ProductQuery();
query.setPageNum(page);
query.setPageSize(size);
if (categoryId != null) {
query.setCategoryId(categoryId);
}
if (StringUtils.isNotBlank(keyword)) {
query.setKeyword(keyword);
}
// 只查询上架商品
query.setStatus(ProductStatus.ON_SALE.getCode());
PageInfo<ProductVO> pageInfo = productService.queryProductList(query);
return Result.success(pageInfo);
}
}
3.2 购物车与订单系统
购物车设计考虑了几个特殊场景:
- 农产品库存变化快,加入购物车时需要二次确认库存
- 支持按农场筛选商品,方便用户集中结算
- 购物车数据同时保存在本地和服务器
订单创建的核心逻辑:
public class OrderServiceImpl implements OrderService {
@Transactional
@Override
public String createOrder(OrderCreateDTO createDTO) {
// 1. 校验商品库存
List<CartItem> cartItems = checkStock(createDTO.getCartItemIds());
// 2. 计算总金额(处理满减、优惠券等)
OrderAmount amount = calculateAmount(cartItems, createDTO.getCouponId());
// 3. 生成订单号(雪花算法)
String orderNo = IdUtil.getSnowflakeNextIdStr();
// 4. 创建订单主表
Order order = new Order();
order.setOrderNo(orderNo);
order.setUserId(createDTO.getUserId());
order.setTotalAmount(amount.getTotalAmount());
order.setPayAmount(amount.getPayAmount());
order.setStatus(OrderStatus.UNPAID.getCode());
order.setExpireTime(DateUtil.offsetMinute(new Date(), 30)); // 30分钟未支付自动取消
orderMapper.insert(order);
// 5. 创建订单商品明细
createOrderItems(order.getId(), cartItems);
// 6. 扣减库存(使用乐观锁)
reduceStock(cartItems);
return orderNo;
}
}
4. 特色功能实现
4.1 农产品溯源功能
为提升消费者信任度,我们设计了完整的溯源链条:
- 农场信息展示(包含资质证书)
- 种植/养殖过程记录
- 检测报告上传
- 物流信息追踪
溯源信息通过QR码关联:
@GetMapping("/trace/{productId}")
public void generateTraceQR(@PathVariable Long productId,
HttpServletResponse response) throws Exception {
String traceUrl = "https://yourdomain.com/trace/detail?productId=" + productId;
// 使用hutool生成QR码
QrConfig config = new QrConfig(300, 300);
config.setMargin(1);
config.setImg("logo.png"); // 添加logo
QrCodeUtil.generate(traceUrl, config, "png", response.getOutputStream());
}
4.2 智能推荐系统
基于用户行为的推荐算法实现:
- 协同过滤推荐相似用户喜欢的商品
- 基于内容的推荐同类农产品
- 热销榜单推荐
推荐服务核心代码:
public List<ProductVO> recommendProducts(Long userId) {
// 1. 获取用户最近浏览记录
List<Long> viewHistory = redisTemplate.opsForList()
.range("user:view:" + userId, 0, 9);
// 2. 获取用户购物车商品
List<Long> cartItems = cartService.getCartProductIds(userId);
// 3. 合并行为数据
Set<Long> seedProducts = new HashSet<>();
seedProducts.addAll(viewHistory);
seedProducts.addAll(cartItems);
// 4. 调用推荐算法
if (seedProducts.isEmpty()) {
return recommendHotProducts(); // 默认返回热销商品
} else {
return cfRecommender.recommend(seedProducts, 10);
}
}
5. 部署与优化实践
5.1 性能优化方案
针对农产品促销时的高并发场景,我们实施了以下优化:
- 缓存策略
- 商品详情使用Redis缓存,设置5分钟过期时间
- 分类列表缓存24小时
- 使用@Cacheable注解简化缓存代码
- 数据库优化
- 为常用查询字段添加索引
- 大文本字段(如商品详情)拆分到单独表
- 使用explain分析慢查询
- 前端优化
- 图片懒加载
- 接口数据分页
- 静态资源CDN加速
5.2 安全防护措施
- 接口安全
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.addFilter(new JwtAuthenticationFilter(authenticationManager()))
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
- 数据安全
- 敏感字段加密存储(如用户手机号)
- 订单数据修改增加操作日志
- 定期备份数据库
6. 开发经验与避坑指南
在实际开发过程中,我们遇到了几个典型问题,这里分享解决方案:
- 农产品库存超卖问题
- 使用MySQL乐观锁控制并发更新
- 扣减库存时验证版本号
public boolean reduceStock(Long productId, Integer quantity) {
int affected = productMapper.reduceStockWithVersion(
productId,
quantity,
product.getVersion());
return affected > 0;
}
- 订单状态同步延迟
- 引入RabbitMQ实现异步通知
- 使用WebSocket推送状态变更
- 增加订单状态补偿机制
- 移动端适配问题
- 使用rem布局适配不同屏幕
- 关键按钮增加触摸反馈
- 表单输入增加防误触处理
这个项目从设计到上线共耗时3个月,核心代码已经过生产环境验证。对于想学习SSM+Vue全栈开发的同学,建议重点关注以下几个文件:
-
ProductController.java- 商品核心逻辑 -
OrderService.java- 订单状态机实现 -
api/product.js- 前端商品接口封装 -
TraceInfo.vue- 溯源页面组件
更多推荐




所有评论(0)