在高校校园环境中,每年都有大量的闲置物品面临流转需求,从毕业生带不走的教材、电器,到新生入学需要添置的生活用品,传统的信息发布方式存在信息不对称、交易效率低下等问题。针对这一特定场景,基于JSP+Servlet技术栈构建的校园二手交易平台应运而生,通过数字化手段为师生提供安全便捷的交易环境。
该平台采用经典的MVC架构模式,Servlet作为控制器层负责处理业务逻辑和请求分发,JSP负责视图渲染,JavaBean作为模型层封装业务数据。数据持久层使用JDBC直接操作MySQL数据库,通过数据库连接池管理资源,确保系统性能。
数据库架构设计
平台数据库包含12个核心表,设计上充分考虑了校园交易场景的特殊性。用户表采用学工号作为唯一标识,确保交易双方的真实性。商品表设计了多级分类体系,支持灵活的品类管理。订单表实现了完整的交易状态跟踪机制。
用户表设计
CREATE TABLE users (
user_id VARCHAR(20) PRIMARY KEY,
password VARCHAR(100) NOT NULL,
real_name VARCHAR(50) NOT NULL,
user_type ENUM('student', 'teacher', 'admin') NOT NULL,
college VARCHAR(100),
major VARCHAR(100),
phone VARCHAR(20),
email VARCHAR(100),
registration_time DATETIME DEFAULT CURRENT_TIMESTAMP,
last_login_time DATETIME,
status ENUM('active', 'inactive') DEFAULT 'active'
);
用户表设计的亮点在于将学工号作为主键,与校园认证体系直接对接。user_type字段区分学生、教师和管理员不同角色,为权限控制奠定基础。status字段支持账户的激活与冻结操作,确保平台安全。
商品表结构
CREATE TABLE items (
item_id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(200) NOT NULL,
description TEXT,
category_id INT NOT NULL,
seller_id VARCHAR(20) NOT NULL,
price DECIMAL(10,2) NOT NULL,
original_price DECIMAL(10,2),
condition ENUM('new', 'like_new', 'good', 'fair') NOT NULL,
images VARCHAR(500),
status ENUM('pending', 'approved', 'sold', 'removed') DEFAULT 'pending',
view_count INT DEFAULT 0,
publish_time DATETIME DEFAULT CURRENT_TIMESTAMP,
approve_time DATETIME,
FOREIGN KEY (seller_id) REFERENCES users(user_id),
FOREIGN KEY (category_id) REFERENCES categories(category_id)
);
商品表通过status字段实现审核机制,所有新发布商品需经管理员审核后才能公开显示。condition字段标准化商品新旧程度描述,减少交易纠纷。images字段存储多图路径,支持商品详情多角度展示。
订单表设计
CREATE TABLE orders (
order_id VARCHAR(30) PRIMARY KEY,
buyer_id VARCHAR(20) NOT NULL,
seller_id VARCHAR(20) NOT NULL,
item_id INT NOT NULL,
quantity INT DEFAULT 1,
total_amount DECIMAL(10,2) NOT NULL,
order_time DATETIME DEFAULT CURRENT_TIMESTAMP,
status ENUM('pending', 'confirmed', 'shipped', 'completed', 'cancelled') DEFAULT 'pending',
payment_method ENUM('online', 'cash') DEFAULT 'cash',
meet_location VARCHAR(200),
buyer_rating TINYINT,
seller_rating TINYINT,
rating_comment TEXT,
FOREIGN KEY (buyer_id) REFERENCES users(user_id),
FOREIGN KEY (seller_id) REFERENCES users(user_id),
FOREIGN KEY (item_id) REFERENCES items(item_id)
);
订单表支持线上线下两种交易方式,meet_location字段记录线下交易地点,符合校园交易特点。双向评价体系为平台信用建设提供数据基础。
核心功能实现
用户认证与权限管理
用户登录采用分层验证机制,根据user_type区分访问权限。Servlet控制器处理登录请求后,将用户信息存入Session供后续权限校验使用。
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userId = request.getParameter("user_id");
String password = request.getParameter("password");
UserDAO userDAO = new UserDAO();
User user = userDAO.authenticate(userId, password);
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("currentUser", user);
session.setAttribute("userType", user.getUserType());
switch (user.getUserType()) {
case "admin":
response.sendRedirect("admin/dashboard.jsp");
break;
case "student":
case "teacher":
response.sendRedirect("user/home.jsp");
break;
}
} else {
request.setAttribute("error", "学工号或密码错误");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}

商品发布与审核流程
商品发布采用多步表单设计,卖家需填写商品基本信息、上传图片、选择分类。后台Servlet处理表单数据,执行图片上传和数据库插入操作。
@WebServlet("/item/publish")
public class ItemPublishServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("currentUser");
if (user == null) {
response.sendRedirect("../login.jsp");
return;
}
String title = request.getParameter("title");
String description = request.getParameter("description");
int categoryId = Integer.parseInt(request.getParameter("category_id"));
BigDecimal price = new BigDecimal(request.getParameter("price"));
String condition = request.getParameter("condition");
// 处理图片上传
String imagePaths = ImageUploader.upload(request);
Item item = new Item();
item.setTitle(title);
item.setDescription(description);
item.setCategoryId(categoryId);
item.setSellerId(user.getUserId());
item.setPrice(price);
item.setCondition(condition);
item.setImages(imagePaths);
ItemDAO itemDAO = new ItemDAO();
boolean success = itemDAO.addItem(item);
if (success) {
response.sendRedirect("publish_success.jsp");
} else {
request.setAttribute("error", "商品发布失败,请重试");
request.getRequestDispatcher("publish.jsp").forward(request, response);
}
}
}
管理员审核界面提供批量操作功能,支持通过、拒绝商品上架申请。审核记录包含时间戳和操作人信息,确保流程可追溯。

购物车与订单处理
购物车基于Session实现临时存储,用户添加商品时Servlet将商品信息存入Session中的购物车列表。
@WebServlet("/cart/add")
public class AddToCartServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int itemId = Integer.parseInt(request.getParameter("item_id"));
int quantity = Integer.parseInt(request.getParameter("quantity", "1"));
HttpSession session = request.getSession();
List<CartItem> cart = (List<CartItem>) session.getAttribute("cart");
if (cart == null) {
cart = new ArrayList<>();
session.setAttribute("cart", cart);
}
// 检查商品是否已在购物车
boolean exists = false;
for (CartItem item : cart) {
if (item.getItemId() == itemId) {
item.setQuantity(item.getQuantity() + quantity);
exists = true;
break;
}
}
if (!exists) {
ItemDAO itemDAO = new ItemDAO();
Item item = itemDAO.getItemById(itemId);
if (item != null && "approved".equals(item.getStatus())) {
CartItem cartItem = new CartItem();
cartItem.setItemId(itemId);
cartItem.setTitle(item.getTitle());
cartItem.setPrice(item.getPrice());
cartItem.setQuantity(quantity);
cartItem.setSellerId(item.getSellerId());
cart.add(cartItem);
}
}
response.sendRedirect("cart.jsp");
}
}

订单生成过程涉及库存检查、价格计算、交易双方确认等环节。Servlet控制器协调各个业务模块,确保数据一致性。
@WebServlet("/order/create")
public class CreateOrderServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
User buyer = (User) session.getAttribute("currentUser");
if (buyer == null) {
response.sendRedirect("../login.jsp");
return;
}
String[] itemIds = request.getParameterValues("item_ids");
String paymentMethod = request.getParameter("payment_method");
String meetLocation = request.getParameter("meet_location");
OrderService orderService = new OrderService();
try {
String orderId = orderService.createOrder(buyer.getUserId(), itemIds,
paymentMethod, meetLocation);
// 清空购物车
session.removeAttribute("cart");
response.sendRedirect("order_detail.jsp?order_id=" + orderId);
} catch (BusinessException e) {
request.setAttribute("error", e.getMessage());
request.getRequestDispatcher("checkout.jsp").forward(request, response);
}
}
}

站内信与通知系统
平台内置消息系统支持买卖双方沟通,消息表设计包含发送者、接收者、消息内容、阅读状态等字段。
@Entity
@Table(name = "messages")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "sender_id", nullable = false)
private String senderId;
@Column(name = "receiver_id", nullable = false)
private String receiverId;
@Column(name = "item_id")
private Integer itemId;
@Column(name = "content", nullable = false, length = 1000)
private String content;
@Column(name = "send_time", nullable = false)
private Timestamp sendTime;
@Column(name = "is_read", nullable = false)
private Boolean read = false;
// getters and setters
}
消息推送采用Ajax轮询机制,用户界面实时显示未读消息数量。

实体模型设计
平台采用面向对象的设计思想,核心实体模型包括用户、商品、订单、分类等。每个实体类封装对应的属性和业务方法,通过DAO模式实现数据访问逻辑分离。
商品实体类
public class Item {
private Integer itemId;
private String title;
private String description;
private Integer categoryId;
private String sellerId;
private BigDecimal price;
private BigDecimal originalPrice;
private String condition;
private String images;
private String status;
private Integer viewCount;
private Date publishTime;
private Date approveTime;
// 关联对象
private User seller;
private Category category;
// 业务方法
public boolean canBeEdited() {
return "pending".equals(status) || "approved".equals(status);
}
public String getMainImage() {
if (images != null && !images.isEmpty()) {
String[] imageArray = images.split(",");
return imageArray[0];
}
return "default.jpg";
}
// getters and setters
}
数据访问层实现
采用JDBC模板模式封装数据库操作,提高代码复用性。
public class ItemDAO {
private DataSource dataSource;
public ItemDAO() {
this.dataSource = DatabaseManager.getDataSource();
}
public List<Item> getItemsByCategory(int categoryId, int page, int pageSize) {
String sql = "SELECT * FROM items WHERE category_id = ? AND status = 'approved' " +
"ORDER BY publish_time DESC LIMIT ?, ?";
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, categoryId);
stmt.setInt(2, (page - 1) * pageSize);
stmt.setInt(3, pageSize);
ResultSet rs = stmt.executeQuery();
List<Item> items = new ArrayList<>();
while (rs.next()) {
Item item = mapResultSetToItem(rs);
items.add(item);
}
return items;
} catch (SQLException e) {
throw new RuntimeException("数据库查询失败", e);
}
}
private Item mapResultSetToItem(ResultSet rs) throws SQLException {
Item item = new Item();
item.setItemId(rs.getInt("item_id"));
item.setTitle(rs.getString("title"));
item.setDescription(rs.getString("description"));
item.setCategoryId(rs.getInt("category_id"));
item.setSellerId(rs.getString("seller_id"));
item.setPrice(rs.getBigDecimal("price"));
item.setCondition(rs.getString("condition"));
item.setImages(rs.getString("images"));
item.setStatus(rs.getString("status"));
item.setViewCount(rs.getInt("view_count"));
item.setPublishTime(rs.getTimestamp("publish_time"));
return item;
}
}
性能优化与安全措施
平台在性能方面采用数据库连接池技术,避免频繁创建连接的开销。页面静态化处理减少JSP编译时间,图片资源使用CDN加速加载。
安全方面实施多层防护:用户密码采用BCrypt加密存储,SQL查询使用预编译语句防止注入攻击,文件上传限制格式和大小,Session超时机制避免会话固定攻击。
功能扩展展望
移动端适配:开发响应式设计或独立的移动APP,满足用户随时随地交易的需求。可采用React Native或Flutter技术实现跨平台移动应用。
智能推荐系统:基于用户浏览历史和购买记录,实现个性化商品推荐。引入协同过滤算法,提升商品发现效率。
在线支付集成:对接校园一卡通或第三方支付平台,支持线上交易担保。需要与学校财务系统对接,确保资金安全。
物流跟踪功能:对于大件物品,集成快递接口实现物流跟踪。可与校园快递服务中心合作,提供优惠配送服务。
信用评价体系:建立完善的用户信用评分机制,基于交易记录、评价内容等维度构建信用模型,促进平台良性发展。
该校园二手交易平台的技术架构体现了传统Java Web技术的成熟稳定,MVC模式的应用保证了代码的可维护性和扩展性。通过严格的校园身份验证和商品审核机制,为师生创造了安全可靠的交易环境,有效促进了校园资源的循环利用。随着技术的不断发展,平台有望通过引入微服务架构、云计算等新技术进一步提升系统性能和用户体验。