基于SSM框架的在线童装销售平台 - 源码深度解析

JavaJavaScriptHTMLCSSSSM框架MySQL
2026-02-0815 浏览

文章摘要

本项目是基于SSM(Spring + Spring MVC + MyBatis)框架构建的在线童装销售平台,旨在为家长和儿童用品采购者提供一个便捷、可靠的线上购物渠道。其核心业务价值在于解决了传统线下童装店品类有限、地域限制强、信息不透明以及消费者比价试穿耗时耗力等痛点。通过集中化的商品展示与在线交...

在童装零售行业数字化转型的浪潮中,一个高效、稳定且易用的在线销售平台成为中小型童装企业的迫切需求。童装优购平台应运而生,该系统基于成熟的SSM(Spring + Spring MVC + MyBatis)技术栈构建,专门针对童装销售场景优化,解决了传统线下零售在品类展示、库存管理、订单处理等方面的痛点。

系统架构与技术栈深度解析

该平台采用经典的三层架构设计,每一层都充分发挥了相应框架的技术优势:

表现层使用Spring MVC框架处理Web请求,通过配置的HandlerMapping将HTTP请求映射到对应的Controller方法。Controller负责接收用户输入,调用业务逻辑层处理,并返回适当的视图(JSP页面)或数据模型。

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private UserService userService;
    
    @RequestMapping("/admin_findAll")
    public String admin_findAll(Model model, HttpServletRequest request) {
        Adminuser adminuserLogin = (Adminuser) request.getSession()
                                    .getAttribute("adminuserLogin");
        if(adminuserLogin == null){
            request.getSession().setAttribute("message", "对不起您还没有登录");
            return "admin/index";
        }
        List<User> userList = userService.admin_findAll();
        model.addAttribute("userList", userList);
        return "admin/user/list";
    }
}

业务逻辑层基于Spring框架的IoC容器管理Bean生命周期和依赖注入,通过AOP机制实现事务管理、日志记录等横切关注点,确保业务逻辑的清晰分离和可维护性。

持久层采用MyBatis框架,通过XML映射文件或注解方式配置SQL语句,避免了传统的JDBC模板代码,同时保持了SQL的灵活性和可优化性。

<!-- ProductMapper.xml 示例 -->
<mapper namespace="com.shop.mapper.ProductMapper">
    <select id="selectByPrimaryKey" parameterType="java.lang.Integer" 
            resultMap="BaseResultMap">
        select * from product where pid = #{pid}
    </select>
    
    <update id="updateProductState" parameterType="map">
        update product set state = #{state} where pid = #{pid}
    </update>
</mapper>

数据库设计亮点与优化策略

商品表设计的精细化考量

product表的设计体现了对电商业务场景的深度理解:

CREATE TABLE `product` (
  `pid` int(11) NOT NULL AUTO_INCREMENT COMMENT '商品ID',
  `pname` varchar(255) DEFAULT NULL COMMENT '商品名称',
  `market_price` double DEFAULT NULL COMMENT '市场价',
  `shop_price` double DEFAULT NULL COMMENT '商城价',
  `image` varchar(255) DEFAULT NULL COMMENT '商品图片',
  `pdesc` varchar(5000) DEFAULT NULL COMMENT '商品描述',
  `is_hot` int(11) DEFAULT NULL COMMENT '是否热销',
  `pdate` date DEFAULT NULL COMMENT '上架日期',
  `csid` int(11) DEFAULT NULL COMMENT '二级分类ID',
  `state` int(11) DEFAULT NULL COMMENT '商品状态',
  PRIMARY KEY (`pid`) USING BTREE,
  KEY `FKED8DCCEF5F778050` (`csid`) USING BTREE,
  CONSTRAINT `FKED8DCCEF5F778050` FOREIGN KEY (`csid`) 
      REFERENCES `categorysecond` (`csid`)
) ENGINE=InnoDB AUTO_INCREMENT=108 DEFAULT CHARSET=utf8 
  COMMENT='商品表'

设计亮点分析:

  1. 价格字段分离market_priceshop_price的分离支持原价与促销价的对比显示,增强营销效果
  2. 描述字段容量优化pdesc字段设置为5000字符,充分满足童装产品详细说明的需求
  3. 状态标志位设计is_hotstate字段使用整型而非布尔型,为未来扩展预留空间
  4. 外键约束优化:通过csid外键关联二级分类表,确保数据完整性

商品管理界面

购物车与订单关联表设计

shopcartitemorderitem表的设计体现了电商业务流程的连贯性:

CREATE TABLE `shopcartitem` (
  `cartitemid` int(11) NOT NULL AUTO_INCREMENT COMMENT '购物车项ID',
  `uid` int(11) DEFAULT NULL COMMENT '用户ID',
  `pid` int(11) DEFAULT NULL COMMENT '商品ID',
  `pcount` int(11) DEFAULT NULL COMMENT '商品数量',
  `price` double DEFAULT NULL COMMENT '商品单价',
  `image` varchar(255) DEFAULT NULL COMMENT '商品图片',
  `ptotal` double DEFAULT NULL COMMENT '商品总价',
  `pname` varchar(255) DEFAULT NULL COMMENT '商品名称',
  PRIMARY KEY (`cartitemid`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='购物车项表'

CREATE TABLE `orderitem` (
  `oiid` int(11) NOT NULL AUTO_INCREMENT COMMENT '订单项ID',
  `count` int(11) DEFAULT NULL COMMENT '商品数量',
  `subtotal` double DEFAULT NULL COMMENT '小计金额',
  `pid` int(11) DEFAULT NULL COMMENT '商品ID',
  `oid` int(11) DEFAULT NULL COMMENT '订单ID',
  PRIMARY KEY (`oiid`) USING BTREE,
  KEY `FKE8B2AB61E818A405` (`oid`) USING BTREE,
  KEY `FKE8B2AB6173B4E627` (`pid`) USING BTREE,
  CONSTRAINT `FKE8B2AB6173B4E627` FOREIGN KEY (`pid`) REFERENCES `product` (`pid`),
  CONSTRAINT `FKE8B2AB61E818A405` FOREIGN KEY (`oid`) REFERENCES `orders` (`oid`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8 COMMENT='订单项表'

性能优化策略:

  1. 冗余字段设计:购物车表中存储商品图片和名称,减少查询时的表连接操作
  2. 金额预计算ptotalsubtotal字段预先计算,避免实时计算的开销
  3. 复合索引优化:订单项表在oidpid上建立索引,提升订单查询效率

核心功能实现深度解析

商品管理模块的实现

商品管理模块采用分层架构,通过ProductService提供完整的CRUD操作:

@Service
public class ProductService {
    @Autowired
    private ProductMapper productMapper;
    
    public PageBean<Product> findByPage(Integer page, Integer limit) {
        PageBean<Product> pageBean = new PageBean<>();
        pageBean.setPage(page);
        pageBean.setLimit(limit);
        
        // 计算开始记录
        int begin = (page - 1) * limit;
        Map<String, Object> map = new HashMap<>();
        map.put("begin", begin);
        map.put("limit", limit);
        
        // 查询分页数据
        List<Product> productList = productMapper.findByPage(map);
        pageBean.setList(productList);
        
        // 查询总记录数
        int totalCount = productMapper.findCount();
        pageBean.setTotalCount(totalCount);
        
        // 计算总页数
        pageBean.setTotalPage((totalCount % limit == 0) ? 
                             (totalCount / limit) : (totalCount / limit + 1));
        
        return pageBean;
    }
    
    public void saveProduct(Product product, MultipartFile upload, 
                           HttpServletRequest request) throws Exception {
        if (!upload.isEmpty()) {
            // 文件上传处理
            String path = request.getSession().getServletContext()
                            .getRealPath("/products/1/");
            String filename = UUIDUtiils.getUUID() + "_" + upload.getOriginalFilename();
            File file = new File(path, filename);
            upload.transferTo(file);
            product.setImage("products/1/" + filename);
        }
        product.setPdate(new Date());
        productMapper.insert(product);
    }
}

商品详情页面

购物车功能的实现机制

购物车功能采用Session与数据库结合的方式,确保用户登录状态的购物车数据持久化:

@Controller
@RequestMapping("/cart")
public class CartController {
    
    @RequestMapping("/addCart")
    public String addCart(Integer pid, Integer count, 
                         HttpServletRequest request) {
        CartItem cartItem = new CartItem();
        Product product = productService.findByPid(pid);
        
        cartItem.setProduct(product);
        cartItem.setCount(count);
        cartItem.setSubtotal(count * product.getShop_price());
        
        Cart cart = getCart(request);
        cart.addCart(cartItem);
        
        return "redirect:/cart/myCart";
    }
    
    private Cart getCart(HttpServletRequest request) {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            request.getSession().setAttribute("cart", cart);
        }
        return cart;
    }
    
    @RequestMapping("/myCart")
    public String myCart(HttpServletRequest request, Model model) {
        User existUser = (User) request.getSession().getAttribute("existUser");
        if (existUser == null) {
            model.addAttribute("message", "请先登录!");
            return "msg";
        }
        return "cart";
    }
}

购物车实体类的设计包含了完整的业务逻辑:

public class Cart {
    private Map<Integer, CartItem> cartItems = new HashMap<>();
    private double total;
    
    public void addCart(CartItem cartItem) {
        Integer pid = cartItem.getProduct().getPid();
        if (cartItems.containsKey(pid)) {
            CartItem existItem = cartItems.get(pid);
            existItem.setCount(existItem.getCount() + cartItem.getCount());
            existItem.setSubtotal(existItem.getCount() * 
                                existItem.getProduct().getShop_price());
        } else {
            cartItems.put(pid, cartItem);
        }
        total += cartItem.getSubtotal();
    }
    
    public void removeCart(Integer pid) {
        CartItem cartItem = cartItems.remove(pid);
        total -= cartItem.getSubtotal();
    }
    
    public void clearCart() {
        cartItems.clear();
        total = 0;
    }
}

购物车界面

订单处理流程的实现

订单模块涉及复杂的业务流程,包括库存检查、金额计算、状态管理等:

@Service
public class OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private ProductMapper productMapper;
    
    @Transactional
    public void save(Order order, Cart cart, HttpServletRequest request) {
        // 1. 保存订单基本信息
        order.setOrdertime(new Date());
        order.setState(1); // 1:未付款 2:已付款 3:已发货 4:已完成
        order.setTotal(cart.getTotal());
        orderMapper.insert(order);
        
        // 2. 保存订单项
        for (CartItem cartItem : cart.getCartItems().values()) {
            OrderItem orderItem = new OrderItem();
            orderItem.setCount(cartItem.getCount());
            orderItem.setSubtotal(cartItem.getSubtotal());
            orderItem.setProduct(cartItem.getProduct());
            orderItem.setOrder(order);
            orderItemMapper.insert(orderItem);
            
            // 3. 更新商品库存
            Product product = cartItem.getProduct();
            product.setStock(product.getStock() - cartItem.getCount());
            productMapper.updateByPrimaryKey(product);
        }
        
        // 4. 清空购物车
        cart.clearCart();
    }
    
    public PageBean<Order> findByUid(Integer uid, Integer page) {
        PageBean<Order> pageBean = new PageBean<>();
        pageBean.setPage(page);
        int limit = 5;
        pageBean.setLimit(limit);
        
        int begin = (page - 1) * limit;
        Map<String, Object> map = new HashMap<>();
        map.put("uid", uid);
        map.put("begin", begin);
        map.put("limit", limit);
        
        List<Order> orderList = orderMapper.findByUid(map);
        pageBean.setList(orderList);
        
        int totalCount = orderMapper.findCountByUid(uid);
        pageBean.setTotalCount(totalCount);
        pageBean.setTotalPage((totalCount % limit == 0) ? 
                             (totalCount / limit) : (totalCount / limit + 1));
        
        return pageBean;
    }
}

订单管理界面

管理员权限控制机制

系统采用基于Session的权限控制,确保管理员操作的安全性:

@Controller
@RequestMapping("/admin")
public class AdminController {
    
    @RequestMapping("/adminLogin")
    public String adminLogin(Adminuser adminuser, Model model, 
                            HttpServletRequest request) {
        Adminuser existAdmin = adminuserService.login(adminuser);
        if (existAdmin == null) {
            model.addAttribute("message", "用户名或密码错误!");
            return "admin/index";
        }
        request.getSession().setAttribute("adminuserLogin", existAdmin);
        return "admin/home";
    }
    
    // 权限检查的AOP实现
    @Before("execution(* com.shop.controller.admin.*.*(..))")
    public void checkAdmin(JoinPoint joinPoint) throws Exception {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = null;
        for (Object arg : args) {
            if (arg instanceof HttpServletRequest) {
                request = (HttpServletRequest) arg;
                break;
            }
        }
        
        if (request != null) {
            Adminuser adminuser = (Adminuser) request.getSession()
                                    .getAttribute("adminuserLogin");
            if (adminuser == null) {
                throw new RuntimeException("管理员未登录!");
            }
        }
    }
}

管理员登录界面

实体模型设计的精妙之处

系统实体模型的设计充分考虑了业务扩展性和数据一致性:

// 商品实体类
public class Product {
    private Integer pid;
    private String pname;
    private Double marketPrice;
    private Double shopPrice;
    private String image;
    private String pdesc;
    private Integer isHot;
    private Date pdate;
    private Integer state;
    
    // 关联属性
    private Categorysecond categorysecond;
    private List<Orderitem> orderitems = new ArrayList<>();
    
    // getter和setter方法
}

// 分类实体类设计支持多级分类
public class Category {
    private Integer cid;
    private String cname;
    private List<Categorysecond> categoryseconds = new ArrayList<>();
}

public class Categorysecond {
    private Integer csid;
    private String csname;
    private Category category;
    private List<Product> products = new ArrayList<>();
}

这种设计支持灵活的商品分类体系,便于实现按年龄、性别、季节等多维度筛选功能。

功能展望与系统优化方向

基于当前系统架构,未来可以从以下几个方向进行深度优化:

1. 引入Redis缓存提升性能

@Service
public class ProductServiceWithCache {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ProductMapper productMapper;
    
    public Product findByIdWithCache(Integer pid) {
        String key = "product:" + pid;
        Product product = (Product) redisTemplate.opsForValue().get(key);
        if (product == null) {
            product = productMapper.selectByPrimaryKey(pid);
            if (product != null) {
                redisTemplate.opsForValue().set(key, product, 30, TimeUnit.MINUTES);
            }
        }
        return product;
    }
}

2. 微服务架构改造

将单体应用拆分为商品服务、订单服务、用户服务等微服务,提升系统可扩展性和维护性。

3. 搜索引擎集成

集成Elasticsearch实现更强大的商品搜索功能,支持拼音搜索、同义词扩展、搜索建议等高级特性。

4. 消息队列异步处理

使用RabbitMQ或Kafka处理高并发场景下的订单创建、库存扣减等操作,提升系统吞吐量。

@Component
public class OrderMessageProducer {
    @Autowired
    private AmqpTemplate rabbitTemplate;
    
    public void sendOrderMessage(Order order) {
        rabbitTemplate.convertAndSend("order.exchange", "order.create", order);
    }
}

@Component
public class OrderMessageConsumer {
    @RabbitListener(queues = "order.queue")
    public void processOrder(Order order) {
        // 异步处理订单业务逻辑
    }
}

5. 移动端适配与PWA技术

开发响应式前端,支持PWA(渐进式Web应用)技术,实现类似原生应用的体验。

总结

童装优购平台通过严谨的SSM架构设计和精细的数据库规划,构建了一个功能完备、性能稳定的电商系统。系统在商品管理、购物车、订单处理等核心模块的实现上体现了良好的工程实践,为中小型童装企业提供了可靠的线上销售解决方案。未来的优化方向将进一步增强系统的可扩展性、性能表现和用户体验,为平台的持续发展奠定坚实基础。

本文关键词
SSM框架在线童装销售平台源码解析童装优购平台MyBatis

上下篇

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