在传统汽配行业数字化转型的浪潮中,一套高效、可靠的在线销售平台成为连接供应商与终端用户的关键基础设施。该系统采用经典的J2EE技术栈构建,以Model 2 MVC设计模式为架构核心,实现了业务逻辑、数据持久化和用户界面的清晰分离。
系统架构严格遵循三层结构设计。表现层由JSP技术承担,负责动态生成用户界面并展示数据;控制层通过Servlet组件接收和处理所有客户端请求,执行业务逻辑并调度页面跳转;模型层则封装了核心业务实体和数据访问对象,通过JDBC与MySQL数据库进行交互。这种架构确保了系统的高内聚低耦合特性,为后续功能扩展和维护提供了坚实基础。
数据库设计深度解析
系统数据库包含10个核心数据表,其中商品表、订单表和用户表的设计尤为关键。商品表采用分类编码机制,通过category_id字段与分类表建立外键关联,支持多级分类体系。
CREATE TABLE product (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
description TEXT,
price DECIMAL(10,2) NOT NULL,
stock INT DEFAULT 0,
category_id INT,
image_url VARCHAR(200),
status TINYINT DEFAULT 1,
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES category(id)
);
订单表设计采用主从表结构,订单头表记录订单基本信息,订单明细表存储商品购买详情。这种设计有效避免了数据冗余,同时支持一个订单包含多个商品项的业务场景。
CREATE TABLE order_header (
id INT PRIMARY KEY AUTO_INCREMENT,
order_no VARCHAR(50) UNIQUE NOT NULL,
user_id INT NOT NULL,
total_amount DECIMAL(10,2) NOT NULL,
status ENUM('pending','paid','shipped','completed','cancelled') DEFAULT 'pending',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
payment_time DATETIME,
FOREIGN KEY (user_id) REFERENCES user(id)
);
CREATE TABLE order_detail (
id INT PRIMARY KEY AUTO_INCREMENT,
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 order_header(id),
FOREIGN KEY (product_id) REFERENCES product(id)
);
用户表采用角色权限分离设计,通过user_type字段区分普通用户和管理员,为不同角色提供差异化的系统功能权限。
核心功能实现机制
商品浏览与搜索功能通过ProductServlet实现,支持按分类筛选和关键词搜索。Servlet接收请求参数后调用ProductService进行数据查询,结果集通过request属性传递到JSP页面渲染。
public class ProductServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String categoryId = request.getParameter("categoryId");
String keyword = request.getParameter("keyword");
ProductService productService = new ProductService();
List<Product> products;
if (categoryId != null && !categoryId.isEmpty()) {
products = productService.getProductsByCategory(Integer.parseInt(categoryId));
} else if (keyword != null && !keyword.isEmpty()) {
products = productService.searchProducts(keyword);
} else {
products = productService.getAllProducts();
}
request.setAttribute("products", products);
request.getRequestDispatcher("/product-list.jsp").forward(request, response);
}
}

购物车管理采用Session存储机制,每个用户的购物车数据在会话期间持久保存。CartServlet负责处理商品的添加、删除和数量修改操作。
public class CartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Map<Integer, CartItem> cart = (Map<Integer, CartItem>) session.getAttribute("cart");
if (cart == null) {
cart = new HashMap<>();
}
String action = request.getParameter("action");
int productId = Integer.parseInt(request.getParameter("productId"));
if ("add".equals(action)) {
int quantity = Integer.parseInt(request.getParameter("quantity"));
Product product = productService.getProductById(productId);
CartItem item = new CartItem(product, quantity);
cart.put(productId, item);
} else if ("remove".equals(action)) {
cart.remove(productId);
}
session.setAttribute("cart", cart);
response.sendRedirect("cart.jsp");
}
}

订单处理流程包含库存校验、价格计算、订单生成等多个环节。OrderService通过事务管理确保数据一致性,防止超卖情况发生。
public class OrderService {
public boolean createOrder(OrderHeader order, List<OrderDetail> details) {
Connection conn = null;
try {
conn = DatabaseUtil.getConnection();
conn.setAutoCommit(false);
// 校验库存
for (OrderDetail detail : details) {
Product product = productService.getProductById(detail.getProductId());
if (product.getStock() < detail.getQuantity()) {
throw new RuntimeException("库存不足: " + product.getName());
}
}
// 插入订单头
orderDao.insertOrderHeader(conn, order);
// 插入订单明细并扣减库存
for (OrderDetail detail : details) {
orderDao.insertOrderDetail(conn, detail);
productDao.updateStock(conn, detail.getProductId(), -detail.getQuantity());
}
conn.commit();
return true;
} catch (Exception e) {
if (conn != null) {
try { conn.rollback(); } catch (SQLException ex) {}
}
return false;
}
}
}

用户认证与授权通过Filter实现统一管控。AuthFilter拦截所有请求,验证用户登录状态和权限等级。
public class AuthFilter 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 path = httpRequest.getRequestURI();
if (path.contains("/admin/")) {
// 管理员权限验证
if (session == null || session.getAttribute("adminUser") == null) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/admin/login.jsp");
return;
}
} else if (path.contains("/user/")) {
// 用户权限验证
if (session == null || session.getAttribute("user") == null) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
return;
}
}
chain.doFilter(request, response);
}
}
实体模型设计
系统核心实体模型采用面向对象设计原则,每个实体类封装对应的业务属性和行为。Product实体包含价格计算、库存状态判断等业务方法。
public class Product {
private Integer id;
private String name;
private String description;
private BigDecimal price;
private Integer stock;
private Integer categoryId;
private String imageUrl;
private Integer status;
private Date createTime;
private Date updateTime;
public boolean isAvailable() {
return status == 1 && stock > 0;
}
public BigDecimal calculateTotal(int quantity) {
return price.multiply(new BigDecimal(quantity));
}
}
Order实体采用组合模式设计,OrderHeader聚合多个OrderDetail对象,完整描述订单业务信息。
public class OrderHeader {
private Integer id;
private String orderNo;
private Integer userId;
private BigDecimal totalAmount;
private String status;
private Date createTime;
private Date paymentTime;
private List<OrderDetail> details;
public void calculateTotal() {
totalAmount = BigDecimal.ZERO;
for (OrderDetail detail : details) {
totalAmount = totalAmount.add(detail.getUnitPrice()
.multiply(new BigDecimal(detail.getQuantity())));
}
}
}
数据访问层优化
系统采用DAO模式实现数据持久化,通过DatabaseUtil管理数据库连接,确保资源正确释放。
public class DatabaseUtil {
public static Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/auto_parts", "username", "password");
} catch (ClassNotFoundException e) {
throw new SQLException("数据库驱动加载失败", e);
}
}
public static void closeConnection(Connection conn) {
if (conn != null) {
try { conn.close(); } catch (SQLException e) {}
}
}
}
ProductDAO封装了所有商品相关的数据库操作,采用预编译语句防止SQL注入攻击。
public class ProductDAO {
public List<Product> getProductsByCategory(int categoryId) throws SQLException {
String sql = "SELECT * FROM product WHERE category_id = ? AND status = 1 ORDER BY create_time DESC";
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DatabaseUtil.getConnection();
stmt = conn.prepareStatement(sql);
stmt.setInt(1, categoryId);
rs = stmt.executeQuery();
List<Product> products = new ArrayList<>();
while (rs.next()) {
products.add(extractProductFromResultSet(rs));
}
return products;
} finally {
DatabaseUtil.closeResultSet(rs);
DatabaseUtil.closeStatement(stmt);
DatabaseUtil.closeConnection(conn);
}
}
}

系统优化与功能扩展方向
性能优化:引入Redis缓存高频访问的商品数据和分类信息,减少数据库查询压力。实现思路:在ProductService层添加缓存逻辑,优先从Redis读取数据,缓存失效时回源到数据库查询。
搜索引擎集成:集成Elasticsearch实现更强大的商品搜索功能,支持拼音搜索、同义词识别和搜索词建议。实现思路:建立商品数据的ES索引,通过RestHighLevelClient实现搜索接口。
支付系统集成:对接支付宝、微信支付等第三方支付平台,完善在线支付流程。实现思路:实现PaymentService抽象层,为不同支付渠道提供统一接口。
库存预警机制:建立库存监控系统,当商品库存低于阈值时自动发送预警通知。实现思路:通过定时任务扫描库存数据,结合消息队列发送预警信息。
移动端适配:开发响应式前端界面或独立的移动端应用,提升移动用户体验。实现思路:采用Bootstrap等前端框架实现响应式布局,或开发基于React Native的移动应用。

该系统通过严谨的架构设计和扎实的技术实现,为汽配行业提供了完整的在线销售解决方案。基于JSP+Servlet的技术选择确保了系统的稳定性和可维护性,而清晰的层次结构为后续功能扩展奠定了良好基础。随着业务需求的不断演进,系统可通过模块化改造和技术栈升级持续提升服务能力。