基于SSM框架的在线鞋类销售商城系统 - 源码深度解析

JavaJavaScriptMavenHTMLCSSSSM框架MySQL
2026-03-283 浏览

文章摘要

本项目是一款基于SSM(Spring + Spring MVC + MyBatis)框架构建的在线鞋类销售商城系统,旨在为鞋类零售商提供一个功能完整、稳定可靠的电子商务解决方案。系统核心业务价值在于打通线上销售渠道,有效解决传统鞋类零售面临的店面成本高、客户覆盖范围有限、库存管理效率低下等核心痛点。...

随着电子商务的蓬勃发展,传统鞋类零售行业面临着数字化转型的迫切需求。鞋类销售商城系统应运而生,该系统基于成熟的SSM框架技术栈构建,为中小型鞋类零售商提供完整的线上销售解决方案。

系统架构与技术栈

系统采用经典的三层架构设计,表现层基于Spring MVC框架实现,通过注解驱动的控制器处理前端请求,利用JSP视图技术进行页面渲染。业务逻辑层依托Spring框架的IoC容器进行Bean管理,通过声明式事务确保核心业务的数据一致性。数据持久层采用MyBatis框架,通过XML映射文件实现对象关系映射,充分发挥动态SQL的优势。

技术栈配置如下:

  • 后端框架:Spring 4.3.7 + Spring MVC 4.3.7 + MyBatis 3.4.2
  • 前端技术:JSP + jQuery + Bootstrap 3.3.7
  • 数据库:MySQL 5.7
  • 项目管理:Maven 3.5
  • 服务器:Tomcat 8.5

数据库设计深度解析

系统数据库包含21张核心表,设计体现了高度的规范化和业务合理性。

用户表设计

CREATE TABLE `user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) NOT NULL UNIQUE,
  `password` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
  `last_login_time` datetime DEFAULT NULL,
  `status` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

用户表采用自增主键设计,username字段设置唯一约束确保用户标识的唯一性。status字段支持软删除功能,create_time和last_login_time分别记录用户注册时间和最后登录时间,为用户行为分析提供数据支撑。

商品表设计

CREATE TABLE `product` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(200) NOT NULL,
  `category_id` int(11) NOT NULL,
  `price` decimal(10,2) NOT NULL,
  `original_price` decimal(10,2) DEFAULT NULL,
  `stock` int(11) NOT NULL DEFAULT '0',
  `description` text,
  `main_image` varchar(500) DEFAULT NULL,
  `detail_images` text,
  `sales_count` int(11) DEFAULT '0',
  `status` tinyint(1) DEFAULT '1',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`product_id`),
  KEY `fk_category` (`category_id`),
  CONSTRAINT `fk_category` FOREIGN KEY (`category_id`) 
  REFERENCES `category` (`category_id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

商品表设计考虑了电商业务的特殊需求,price和original_price字段支持促销价格展示,stock字段实时跟踪库存数量。detail_images字段采用JSON格式存储多张详情图片,sales_count字段记录销量用于热门商品排序。update_time字段通过ON UPDATE CURRENT_TIMESTAMP自动更新时间戳。

订单表设计

CREATE TABLE `orders` (
  `order_id` varchar(32) NOT NULL,
  `user_id` int(11) NOT NULL,
  `total_amount` decimal(10,2) NOT NULL,
  `payment_amount` decimal(10,2) NOT NULL,
  `payment_method` tinyint(1) DEFAULT '1',
  `payment_time` datetime DEFAULT NULL,
  `order_status` tinyint(1) DEFAULT '0',
  `shipping_address` text NOT NULL,
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`order_id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

订单表采用字符串类型的主键,便于生成具有业务意义的订单编号。total_amount和payment_amount分别记录订单原实付金额,payment_time记录支付时间,order_status使用状态码管理订单生命周期。复合索引设计优化了用户订单查询和时间范围查询性能。

核心功能实现详解

用户认证与权限管理

系统采用基于角色的访问控制模型,用户登录后根据角色权限展示不同的功能菜单。Spring Security集成实现了安全的认证机制。

@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("userType", user.getUserType());
            } else {
                result.put("success", false);
                result.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "登录异常");
        }
        return ResponseEntity.ok(result);
    }
}

用户登录界面

商品搜索与分页展示

商品搜索功能支持多条件复合查询,包括关键词搜索、价格区间、分类筛选等。MyBatis的动态SQL特性有效处理了复杂的查询条件组合。

<!-- 商品搜索动态SQL -->
<select id="searchProducts" parameterType="map" resultMap="ProductResultMap">
    SELECT * FROM product 
    WHERE status = 1
    <if test="keyword != null and keyword != ''">
        AND (product_name LIKE CONCAT('%', #{keyword}, '%') 
             OR description LIKE CONCAT('%', #{keyword}, '%'))
    </if>
    <if test="categoryId != null">
        AND category_id = #{categoryId}
    </if>
    <if test="minPrice != null">
        AND price >= #{minPrice}
    </if>
    <if test="maxPrice != null">
        AND price &lt;= #{maxPrice}
    </if>
    <if test="orderBy != null">
        ORDER BY 
        <choose>
            <when test="orderBy == 'price_asc'">price ASC</when>
            <when test="orderBy == 'price_desc'">price DESC</when>
            <when test="orderBy == 'sales'">sales_count DESC</when>
            <when test="orderBy == 'newest'">create_time DESC</when>
        </choose>
    </if>
    LIMIT #{start}, #{pageSize}
</select>

商品搜索界面

购物车与订单处理

购物车功能采用Session与数据库双重存储策略,确保用户数据的持久化和一致性。订单处理过程包含完整的库存校验和事务管理。

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Override
    public Order createOrder(OrderDTO orderDTO) {
        // 验证库存
        for (OrderItemDTO item : orderDTO.getItems()) {
            Product product = productMapper.selectById(item.getProductId());
            if (product.getStock() < item.getQuantity()) {
                throw new BusinessException("商品库存不足: " + product.getProductName());
            }
        }
        
        // 生成订单
        Order order = new Order();
        order.setOrderId(generateOrderId());
        order.setUserId(orderDTO.getUserId());
        order.setTotalAmount(calculateTotalAmount(orderDTO.getItems()));
        order.setOrderStatus(OrderStatus.UNPAID);
        
        orderMapper.insert(order);
        
        // 扣减库存
        for (OrderItemDTO item : orderDTO.getItems()) {
            productMapper.decreaseStock(item.getProductId(), item.getQuantity());
        }
        
        return order;
    }
    
    private String generateOrderId() {
        return System.currentTimeMillis() + 
               String.valueOf(new Random().nextInt(9000) + 1000);
    }
}

购物车界面

后台商品管理

管理员后台提供完整的商品CRUD操作,支持图片上传、批量操作等高级功能。文件上传采用Apache Commons FileUpload组件实现。

@Controller
@RequestMapping("/admin/product")
public class AdminProductController {
    
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadImage(
            @RequestParam("file") MultipartFile file) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "请选择要上传的文件");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (!Arrays.asList("image/jpeg", "image/png", "image/gif").contains(contentType)) {
                result.put("success", false);
                result.put("message", "只支持JPEG、PNG、GIF格式的图片");
                return ResponseEntity.badRequest().body(result);
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;
            
            // 保存文件
            File dest = new File(uploadPath + newFilename);
            file.transferTo(dest);
            
            result.put("success", true);
            result.put("filePath", "/uploads/" + newFilename);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "文件上传失败");
        }
        
        return ResponseEntity.ok(result);
    }
}

商品管理界面

实体模型设计

系统核心实体模型采用面向对象的设计理念,通过MyBatis的映射机制实现数据持久化。

订单实体与明细关系

public class Order {
    private String orderId;
    private Integer userId;
    private BigDecimal totalAmount;
    private OrderStatus orderStatus;
    private Date createTime;
    private List<OrderItem> orderItems;
    
    // 计算订单总金额
    public BigDecimal calculateTotalAmount() {
        return orderItems.stream()
                .map(item -> item.getPrice().multiply(new BigDecimal(item.getQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

public class OrderItem {
    private Long itemId;
    private String orderId;
    private Integer productId;
    private String productName;
    private BigDecimal price;
    private Integer quantity;
    private String productImage;
}

商品分类树形结构

public class Category {
    private Integer categoryId;
    private String categoryName;
    private Integer parentId;
    private Integer level;
    private Integer sortOrder;
    private List<Category> children;
    
    // 构建分类树
    public static List<Category> buildTree(List<Category> categories) {
        Map<Integer, Category> categoryMap = categories.stream()
                .collect(Collectors.toMap(Category::getCategoryId, Function.identity()));
        
        List<Category> rootCategories = new ArrayList<>();
        for (Category category : categories) {
            if (category.getParentId() == 0) {
                rootCategories.add(category);
            } else {
                Category parent = categoryMap.get(category.getParentId());
                if (parent != null) {
                    parent.addChild(category);
                }
            }
        }
        return rootCategories;
    }
}

系统优化与扩展方向

性能优化策略

  1. 缓存层集成:引入Redis作为二级缓存,缓存热点商品数据、用户会话信息,减轻数据库压力
  2. 数据库读写分离:配置MySQL主从复制,实现读写操作分离,提升系统并发处理能力
  3. 静态资源CDN加速:商品图片等静态资源部署至CDN,提升页面加载速度

功能扩展建议

  1. 推荐算法集成:基于用户行为数据实现协同过滤推荐,提升商品转化率
  2. 多商户支持:扩展系统架构支持多商户入驻,打造鞋类电商平台
  3. 移动端适配:开发响应式前端或独立移动App,满足移动购物需求
  4. 物流跟踪集成:对接第三方物流API,实现订单物流实时跟踪
  5. 数据分析看板:构建BI数据分析模块,为经营决策提供数据支持

安全增强措施

  1. 支付安全加固:集成微信支付、支付宝官方SDK,实现安全的支付流程
  2. SQL注入防护:全面使用MyBatis参数化查询,防范SQL注入攻击
  3. XSS攻击防护:在前端和后端同时实施输入验证和输出编码

系统通过严谨的架构设计和细致的功能实现,为鞋类零售企业提供了稳定可靠的电商解决方案。模块化的设计使得系统具备良好的可扩展性,为后续的功能升级和技术演进奠定了坚实基础。

本文关键词
SSM框架在线商城鞋类销售系统架构数据库设计

上下篇

上一篇
没有更多文章
下一篇
没有更多文章