在传统甜品店运营中,手工记录订单和库存管理往往导致效率低下和错误频发。订单信息可能遗漏或重复,库存更新不及时容易引发超卖或原料浪费,直接影响店铺的盈利能力和顾客体验。针对这些痛点,一套集成在线点餐与库存管理功能的系统成为中小型甜品店的迫切需求。
本系统采用经典的JSP+Servlet技术栈构建,严格遵循MVC设计模式,实现了前后端数据的高效同步。系统将顾客点餐流程全面线上化,同时为管理员提供实时的库存监控和预警功能,有效解决了传统管理方式的弊端。

技术架构深度解析
系统采用三层架构设计,表现层由JSP页面负责,通过JSTL标签和EL表达式实现数据动态展示,完全避免了在页面中嵌入Java代码,保证了代码的整洁性和可维护性。控制层核心由Servlet实现,每个Servlet对应特定的业务模块,如用户登录、商品管理、订单处理等,负责请求的接收、参数验证和业务逻辑调度。
模型层由JavaBean组件构成,封装了所有的数据操作逻辑。数据库连接采用JDBC技术,通过连接池管理提高性能。事务管理确保了点餐操作与库存更新的原子性,防止数据不一致的情况发生。
// 数据库连接工具类核心代码
public class DBUtil {
private static DataSource dataSource;
static {
try {
Context initContext = new InitialContext();
dataSource = (DataSource) initContext.lookup("java:/comp/env/jdbc/cakeshop");
} catch (NamingException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
数据库设计亮点分析
系统数据库包含6个核心表,设计上充分考虑了业务逻辑的完整性和数据一致性。其中商品表(products)和订单表(orders)的设计尤为关键。
商品表不仅存储基本的商品信息,还包含库存状态管理和销售状态控制字段。stock_quantity字段实时记录库存数量,status字段控制商品在前端的显示状态,当库存为0时自动下架商品。
CREATE TABLE products (
product_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description TEXT,
price DECIMAL(10,2) NOT NULL,
stock_quantity INT NOT NULL DEFAULT 0,
category_id INT,
image_url VARCHAR(200),
status ENUM('active','inactive') DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES categories(category_id)
);
订单表采用主从表结构设计,主表(orders)记录订单基本信息,从表(order_items)详细记录每个订单的商品明细。这种设计支持一个订单包含多个商品,同时便于库存扣减和销售统计。
CREATE TABLE orders (
order_id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
total_amount DECIMAL(10,2) NOT NULL,
status ENUM('pending','paid','shipped','completed','cancelled') DEFAULT 'pending',
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
shipping_address TEXT,
payment_method VARCHAR(50),
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
CREATE TABLE order_items (
item_id INT AUTO_INCREMENT PRIMARY KEY,
order_id INT NOT NULL,
product_id INT NOT NULL,
quantity INT NOT NULL,
unit_price DECIMAL(10,2) NOT NULL,
FOREIGN KEY (order_id) REFERENCES orders(order_id),
FOREIGN KEY (product_id) REFERENCES products(product_id)
);
核心功能实现深度解析
1. 智能库存管理机制
系统实现了库存的实时监控和自动预警。当顾客下单时,系统会立即扣减相应商品的库存数量,并通过触发器机制检查库存阈值。当库存低于预设的安全库存时,系统会自动标记并通知管理员。
// 库存扣减核心逻辑
public boolean updateProductStock(int productId, int quantity) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DBUtil.getConnection();
conn.setAutoCommit(false);
// 检查当前库存
String checkSQL = "SELECT stock_quantity FROM products WHERE product_id = ?";
pstmt = conn.prepareStatement(checkSQL);
pstmt.setInt(1, productId);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
int currentStock = rs.getInt("stock_quantity");
if (currentStock < quantity) {
throw new RuntimeException("库存不足");
}
}
// 更新库存
String updateSQL = "UPDATE products SET stock_quantity = stock_quantity - ? WHERE product_id = ?";
pstmt = conn.prepareStatement(updateSQL);
pstmt.setInt(1, quantity);
pstmt.setInt(2, productId);
int affectedRows = pstmt.executeUpdate();
conn.commit();
return affectedRows > 0;
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
return false;
} finally {
DBUtil.closeResources(conn, pstmt, null);
}
}

2. 购物车与订单处理流程
购物车功能采用Session存储机制,用户添加商品时,系统会将商品信息临时存储在用户会话中。提交订单时,系统会验证每个商品的库存状态,确保订单的可行性。
// 购物车添加商品Servlet
@WebServlet("/addToCart")
public class AddToCartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int productId = Integer.parseInt(request.getParameter("productId"));
int quantity = Integer.parseInt(request.getParameter("quantity"));
HttpSession session = request.getSession();
Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
if (cart == null) {
cart = new HashMap<>();
session.setAttribute("cart", cart);
}
Product product = productService.getProductById(productId);
if (product != null && product.getStockQuantity() >= quantity) {
CartItem item = cart.get(productId);
if (item != null) {
item.setQuantity(item.getQuantity() + quantity);
} else {
item = new CartItem(product, quantity);
cart.put(productId, item);
}
}
response.sendRedirect("cart.jsp");
}
}

3. 用户身份验证与权限控制
系统采用基于角色的访问控制机制,区分普通用户和管理员两种身份。登录验证通过后,系统会将用户信息存储在Session中,并通过过滤器对敏感操作进行权限校验。
// 登录验证Servlet
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.authenticate(username, password);
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("currentUser", user);
session.setMaxInactiveInterval(30 * 60); // 30分钟超时
if ("admin".equals(user.getRole())) {
response.sendRedirect("admin/dashboard.jsp");
} else {
response.sendRedirect("index.jsp");
}
} else {
request.setAttribute("errorMessage", "用户名或密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}

4. 商品分类与搜索功能
系统支持多级商品分类管理,管理员可以动态添加、修改商品分类。前端页面通过AJAX技术实现分类筛选和关键词搜索,提升用户体验。
<%-- 商品分类展示JSP片段 --%>
<div class="category-filter">
<c:forEach var="category" items="${categories}">
<button class="category-btn" data-category="${category.categoryId}">
${category.categoryName}
</button>
</c:forEach>
</div>
<div class="product-grid">
<c:forEach var="product" items="${products}">
<div class="product-card" data-category="${product.categoryId}">
<img src="${product.imageUrl}" alt="${product.name}">
<h3>${product.name}</h3>
<p class="price">¥${product.price}</p>
<c:if test="${product.stockQuantity > 0}">
<button class="add-to-cart" data-product="${product.productId}">加入购物车</button>
</c:if>
<c:if test="${product.stockQuantity <= 0}">
<button class="out-of-stock" disabled>已售罄</button>
</c:if>
</div>
</c:forEach>
</div>

实体模型设计精要
系统实体模型设计充分体现了业务领域的核心概念。User实体包含用户基本信息和角色权限,Product实体封装商品属性及库存状态,Order实体管理订单生命周期,Category实体支持商品分类体系。
// 订单实体类
public class Order {
private int orderId;
private int userId;
private BigDecimal totalAmount;
private String status;
private Date orderDate;
private String shippingAddress;
private String paymentMethod;
private List<OrderItem> orderItems;
// 构造函数、getter和setter方法
public Order() {}
public BigDecimal calculateTotal() {
BigDecimal total = BigDecimal.ZERO;
if (orderItems != null) {
for (OrderItem item : orderItems) {
total = total.add(item.getUnitPrice()
.multiply(BigDecimal.valueOf(item.getQuantity())));
}
}
return total;
}
}
性能优化与安全考量
系统在性能方面采用了数据库连接池技术,避免频繁创建和关闭连接带来的开销。通过预编译语句防止SQL注入攻击,对用户输入进行严格的验证和过滤。
事务管理确保关键业务操作(如创建订单同时更新库存)的原子性,使用数据库事务特性保证数据一致性。Session超时机制和权限验证过滤器有效防止未授权访问。
// 权限验证过滤器
@WebFilter("/*")
public class AuthenticationFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = httpRequest.getSession(false);
String requestURI = httpRequest.getRequestURI();
// 公开访问路径
if (requestURI.endsWith("login.jsp") || requestURI.endsWith("register.jsp") ||
requestURI.endsWith("login") || requestURI.endsWith("register") ||
requestURI.contains("/assets/")) {
chain.doFilter(request, response);
return;
}
// 管理员路径权限验证
if (requestURI.contains("/admin/")) {
if (session != null && session.getAttribute("currentUser") != null) {
User user = (User) session.getAttribute("currentUser");
if ("admin".equals(user.getRole())) {
chain.doFilter(request, response);
} else {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/access-denied.jsp");
}
} else {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/admin-login.jsp");
}
return;
}
chain.doFilter(request, response);
}
}

系统扩展与优化方向
移动端适配与响应式设计:当前系统主要面向桌面端使用,未来可引入Bootstrap等前端框架实现真正的响应式布局,提升移动设备用户体验。
第三方支付集成:集成微信支付、支付宝等主流支付方式,简化支付流程。可通过支付SDK和回调接口实现安全的支付处理。
数据分析和报表功能:增加销售数据分析模块,通过图表展示热销商品、时段销售趋势等,为经营决策提供数据支持。
会员积分体系:建立会员等级和积分系统,通过积分兑换、会员折扣等机制增强客户粘性。
多店铺支持架构:重构系统架构支持多店铺模式,不同分店可独立管理商品和订单,总部统一监控各店运营情况。
该系统通过合理的技术选型和严谨的架构设计,成功解决了甜品店日常运营中的核心痛点。基于JSP+Servlet的成熟技术栈保证了系统的稳定性和可维护性,清晰的MVC分层为后续功能扩展奠定了良好基础。随着业务的发展,系统可通过模块化扩展持续满足店铺不断变化的管理需求。