在电子商务蓬勃发展的时代,专业细分市场的在线销售平台需求日益凸显。童鞋市场作为一个具有特定用户群体和产品特性的垂直领域,对线上商城系统提出了独特的要求。该系统正是针对这一市场需求,采用成熟的SSM技术栈构建的一个功能完备、性能稳定的B2C在线销售解决方案。
系统架构与技术栈选型
该系统采用经典的三层架构模式,基于SSM框架集进行深度整合。Spring Framework作为核心控制容器,负责管理所有业务组件的生命周期和依赖关系,通过控制反转和依赖注入机制实现组件间的松耦合。Spring MVC框架承担Web请求的分发和处理职责,利用注解驱动的控制器简化开发流程,同时通过拦截器实现统一的权限验证和日志记录。数据持久层选用MyBatis框架,其灵活的SQL映射机制能够精确控制数据库操作,兼顾开发效率与性能优化。
前端展示层采用JSP技术结合JSTL标签库进行页面渲染,集成jQuery库处理客户端交互逻辑。项目使用Maven进行依赖管理和构建部署,确保第三方库版本的一致性和项目可移植性。数据库采用MySQL关系型数据库,通过合理的表结构设计和索引优化保障数据操作的效率。
数据库设计亮点解析
系统的数据库设计体现了电商业务的复杂性,共包含11张核心数据表。其中商品信息表的设计尤为值得关注:
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL COMMENT '商品名称',
`category_id` int(11) NOT NULL COMMENT '分类ID',
`brand_id` int(11) NOT NULL COMMENT '品牌ID',
`price` decimal(10,2) NOT NULL COMMENT '销售价格',
`original_price` decimal(10,2) DEFAULT NULL COMMENT '原价',
`stock` int(11) NOT NULL DEFAULT '0' COMMENT '库存数量',
`size_range` varchar(50) DEFAULT NULL COMMENT '尺码范围',
`age_range` varchar(30) DEFAULT NULL COMMENT '适用年龄',
`main_image` varchar(200) DEFAULT NULL COMMENT '主图URL',
`detail_images` text COMMENT '详情图URL集合',
`description` text COMMENT '商品描述',
`sales_count` int(11) DEFAULT '0' COMMENT '销售数量',
`status` tinyint(1) DEFAULT '1' COMMENT '上下架状态',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_category` (`category_id`),
KEY `idx_brand` (`brand_id`),
KEY `idx_price` (`price`),
KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品信息表';
该表设计充分考虑了童鞋商品的特殊属性,如尺码范围、适用年龄等字段,体现了垂直电商领域的数据模型特点。通过多维度索引优化,确保在商品搜索、分类筛选等高频操作场景下的查询性能。
订单表的设计则体现了电商交易的完整性要求:
CREATE TABLE `orders` (
`id` varchar(32) NOT NULL COMMENT '订单号',
`user_id` int(11) NOT NULL COMMENT '用户ID',
`total_amount` decimal(10,2) NOT NULL COMMENT '订单总金额',
`payment_amount` decimal(10,2) DEFAULT NULL COMMENT '实付金额',
`payment_method` tinyint(1) DEFAULT NULL COMMENT '支付方式',
`payment_time` datetime DEFAULT NULL COMMENT '支付时间',
`status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '订单状态',
`shipping_address` text NOT NULL COMMENT '收货地址',
`receiver_name` varchar(50) NOT NULL COMMENT '收货人姓名',
`receiver_phone` varchar(20) NOT NULL COMMENT '收货人电话',
`order_notes` varchar(200) DEFAULT NULL COMMENT '订单备注',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_user_id` (`user_id`),
KEY `idx_status` (`status`),
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单表';
采用字符串类型的订单号便于业务扩展和分布式环境下的唯一性保证。订单状态字段的设计支持完整的订单生命周期管理,从待支付到已完成的全流程跟踪。
核心业务功能实现
用户认证与权限控制
系统通过Spring拦截器实现统一的用户认证机制,确保敏感操作必须经过登录验证。以下是用户登录的核心处理逻辑:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
@ResponseBody
public ResponseEntity<Map<String, Object>> login(
@RequestParam String username,
@RequestParam String password,
HttpSession session) {
Map<String, Object> result = new HashMap<>();
try {
User user = userService.authenticate(username, password);
if (user != null) {
session.setAttribute("currentUser", user);
result.put("success", true);
result.put("message", "登录成功");
result.put("userInfo", user);
} else {
result.put("success", false);
result.put("message", "用户名或密码错误");
}
} catch (Exception e) {
result.put("success", false);
result.put("message", "登录异常:" + e.getMessage());
}
return ResponseEntity.ok(result);
}
}

权限控制通过自定义注解和AOP切面实现,对不同角色的用户访问权限进行精细化管理:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireRole {
UserRole value() default UserRole.USER;
}
@Component
@Aspect
public class AuthorizationAspect {
@Around("@annotation(requireRole)")
public Object checkPermission(ProceedingJoinPoint joinPoint,
RequireRole requireRole) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.getRequestAttributes()).getRequest();
User user = (User) request.getSession().getAttribute("currentUser");
if (user == null) {
throw new AuthorizationException("用户未登录");
}
if (user.getRole().getLevel() < requireRole.value().getLevel()) {
throw new AuthorizationException("权限不足");
}
return joinPoint.proceed();
}
}
商品搜索与分类展示
商品检索功能支持多条件组合查询,通过MyBatis的动态SQL实现灵活的查询条件构建:
<!-- 商品查询映射配置 -->
<select id="selectByCondition" parameterType="map" resultMap="ProductResultMap">
SELECT p.*, c.name as category_name, b.name as brand_name
FROM product p
LEFT JOIN category c ON p.category_id = c.id
LEFT JOIN brand b ON p.brand_id = b.id
WHERE p.status = 1
<if test="categoryId != null">
AND p.category_id = #{categoryId}
</if>
<if test="brandId != null">
AND p.brand_id = #{brandId}
</if>
<if test="minPrice != null">
AND p.price >= #{minPrice}
</if>
<if test="maxPrice != null">
AND p.price <= #{maxPrice}
</if>
<if test="keyword != null and keyword != ''">
AND (p.name LIKE CONCAT('%', #{keyword}, '%')
OR p.description LIKE CONCAT('%', #{keyword}, '%'))
</if>
<if test="ageRange != null">
AND p.age_range = #{ageRange}
</if>
ORDER BY
<choose>
<when test="sortField == 'price'">
p.price ${sortOrder}
</when>
<when test="sortField == 'sales'">
p.sales_count ${sortOrder}
</when>
<when test="sortField == 'time'">
p.create_time ${sortOrder}
</when>
<otherwise>
p.create_time DESC
</otherwise>
</choose>
LIMIT #{offset}, #{pageSize}
</select>

购物车与订单处理
购物车功能采用Session与数据库双存储策略,确保用户数据的持久化和临时存储的灵活性:
@Service
@Transactional
public class CartServiceImpl implements CartService {
@Autowired
private CartItemMapper cartItemMapper;
@Override
public void addToCart(Integer userId, Integer productId, Integer quantity) {
// 检查库存
Product product = productService.getProductById(productId);
if (product.getStock() < quantity) {
throw new BusinessException("库存不足");
}
// 检查购物车中是否已存在该商品
CartItem existingItem = cartItemMapper.selectByUserAndProduct(userId, productId);
if (existingItem != null) {
existingItem.setQuantity(existingItem.getQuantity() + quantity);
cartItemMapper.updateQuantity(existingItem);
} else {
CartItem newItem = new CartItem();
newItem.setUserId(userId);
newItem.setProductId(productId);
newItem.setQuantity(quantity);
newItem.setUnitPrice(product.getPrice());
cartItemMapper.insert(newItem);
}
}
@Override
@Transactional
public String createOrder(Integer userId, List<CartItem> cartItems,
ShippingAddress address) {
// 生成订单号
String orderId = generateOrderId();
// 计算总金额
BigDecimal totalAmount = calculateTotalAmount(cartItems);
// 创建订单主记录
Order order = new Order();
order.setId(orderId);
order.setUserId(userId);
order.setTotalAmount(totalAmount);
order.setShippingAddress(JSON.toJSONString(address));
order.setStatus(OrderStatus.PENDING_PAYMENT);
orderMapper.insert(order);
// 创建订单明细
for (CartItem item : cartItems) {
OrderItem orderItem = new OrderItem();
orderItem.setOrderId(orderId);
orderItem.setProductId(item.getProductId());
orderItem.setQuantity(item.getQuantity());
orderItem.setUnitPrice(item.getUnitPrice());
orderItemMapper.insert(orderItem);
// 扣减库存
productMapper.decreaseStock(item.getProductId(), item.getQuantity());
}
// 清空购物车
cartItemMapper.deleteByUserId(userId);
return orderId;
}
}

后台管理系统
后台管理模块提供了完整的商品管理、订单处理、用户管理等功能,采用RBAC权限模型实现多角色管理:
@RestController
@RequestMapping("/admin")
public class AdminProductController {
@Autowired
private ProductService productService;
@PostMapping("/product/save")
@RequireRole(UserRole.ADMIN)
public ResponseEntity<ApiResponse> saveProduct(@RequestBody Product product,
@RequestParam MultipartFile mainImage,
@RequestParam MultipartFile[] detailImages) {
try {
// 处理图片上传
String mainImagePath = fileService.uploadImage(mainImage);
product.setMainImage(mainImagePath);
List<String> detailImagePaths = new ArrayList<>();
for (MultipartFile image : detailImages) {
String path = fileService.uploadImage(image);
detailImagePaths.add(path);
}
product.setDetailImages(JSON.toJSONString(detailImagePaths));
if (product.getId() == null) {
productService.addProduct(product);
} else {
productService.updateProduct(product);
}
return ResponseEntity.ok(ApiResponse.success("操作成功"));
} catch (Exception e) {
return ResponseEntity.badRequest()
.body(ApiResponse.error("操作失败:" + e.getMessage()));
}
}
@GetMapping("/products")
@RequireRole(UserRole.ADMIN)
public ResponseEntity<PageResult<Product>> getProductList(
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size,
ProductQuery query) {
PageResult<Product> result = productService.getProductsByPage(page, size, query);
return ResponseEntity.ok(result);
}
}

实体模型设计
系统的领域模型设计严格遵循电商业务的实体关系,核心实体包括用户、商品、订单、购物车等:
// 商品实体类
@Data
@TableName("product")
public class Product {
private Integer id;
private String name;
private Integer categoryId;
private Integer brandId;
private BigDecimal price;
private BigDecimal originalPrice;
private Integer stock;
private String sizeRange;
private String ageRange;
private String mainImage;
private String detailImages;
private String description;
private Integer salesCount;
private Boolean status;
private Date createTime;
private Date updateTime;
// 关联对象
private Category category;
private Brand brand;
private List<ProductSku> skus;
}
// 订单实体类
@Data
@TableName("orders")
public class Order {
private String id;
private Integer userId;
private BigDecimal totalAmount;
private BigDecimal paymentAmount;
private Integer paymentMethod;
private Date paymentTime;
private Integer status;
private String shippingAddress;
private String receiverName;
private String receiverPhone;
private String orderNotes;
private Date createTime;
private Date updateTime;
// 关联数据
private User user;
private List<OrderItem> orderItems;
private ShippingAddress addressInfo;
}
性能优化与安全考虑
系统在性能优化方面采取了多项措施。数据库层面通过合理的索引设计和查询优化提升数据检索效率。应用层使用连接池技术管理数据库连接,减少连接创建开销。对频繁访问的商品信息等数据实施缓存策略,降低数据库压力。
安全方面,系统实现了完整的用户密码加密存储、SQL注入防护、XSS攻击防范等安全机制。敏感操作如支付、密码修改等均进行二次验证,确保业务安全性。
功能扩展展望
基于现有系统架构,未来可考虑以下扩展方向:
移动端适配:开发响应式前端或独立的移动APP,满足移动购物趋势。可采用Vue.js或React重构前端,通过RESTful API与后端交互。
智能推荐系统:集成机器学习算法,基于用户浏览和购买历史实现个性化商品推荐。需要构建用户行为数据收集和分析管道。
社交媒体集成:增加微信、微博等社交平台登录和分享功能,利用社交网络扩大用户群体。需要实现OAuth2.0授权流程。
多商户支持:扩展为平台模式,支持多个商家入驻,需要重构用户权限体系和结算逻辑。
数据分析看板:为商家提供销售数据可视化分析,辅助经营决策。需要集成ELK栈或类似的数据分析工具。
该系统作为SSM技术栈在电商领域的典型应用,展示了传统Java Web技术在现代业务场景下的实用性和稳定性。其清晰的架构设计和完整的业务实现为类似项目的开发提供了有价值的参考。