在数字化校园建设浪潮中,短途出行效率成为影响师生工作学习体验的关键因素之一。传统校园自行车租赁依赖人工登记、现金结算的方式,存在流程繁琐、车辆状态不透明、数据统计困难等痛点。为此,我们设计并实现了一套基于JSP+Servlet技术的校园自行车智能租赁平台,通过模块化设计实现了车辆管理、用户服务、财务结算的全流程数字化管控。
系统采用经典的三层架构模式,表现层使用JSP动态页面技术结合HTML/CSS/JavaScript完成用户交互界面渲染,业务逻辑层通过Servlet控制器接收前端请求并调用相应的Service服务模块,数据持久层基于JDBC规范封装DAO数据访问对象,实现对MySQL数据库的原子化操作。这种架构确保了业务逻辑与视图分离,提高了代码的可维护性和扩展性。
数据库架构设计精要
系统共设计13张数据表,核心表结构体现了严谨的业务逻辑关系。以自行车信息表(bicycle)为例,其设计不仅包含基础属性,还通过状态标识实现了业务闭环:
CREATE TABLE bicycle (
bicycle_id INT PRIMARY KEY AUTO_INCREMENT,
bicycle_number VARCHAR(20) NOT NULL UNIQUE,
type_id INT NOT NULL,
site_id INT NOT NULL,
status ENUM('available', 'rented', 'maintenance') DEFAULT 'available',
purchase_date DATE,
last_maintenance_date DATE,
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (type_id) REFERENCES bicycle_type(type_id),
FOREIGN KEY (site_id) REFERENCES rental_site(site_id)
);
该表通过status字段精确控制车辆生命周期,利用外键约束确保数据一致性。purchase_date和last_maintenance_date字段为运维管理提供了数据支撑。
租赁记录表(lease_record)的设计则体现了复杂业务状态流转的精细化管控:
CREATE TABLE lease_record (
record_id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL,
bicycle_id INT NOT NULL,
lease_time DATETIME NOT NULL,
expected_return_time DATETETIME,
actual_return_time DATETETIME,
lease_site_id INT NOT NULL,
return_site_id INT,
cost DECIMAL(10,2),
payment_status ENUM('pending', 'paid', 'refunded') DEFAULT 'pending',
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(user_id),
FOREIGN KEY (bicycle_id) REFERENCES bicycle(bicycle_id)
);
通过expected_return_time与actual_return_time的时间差计算租赁费用,payment_status字段完整记录支付流程,lease_site_id和return_site_id支持跨站点还车功能。
用户账户表(user_account)采用事务安全的设计方案:
CREATE TABLE user_account (
account_id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL UNIQUE,
balance DECIMAL(10,2) DEFAULT 0.00,
total_recharge DECIMAL(10,2) DEFAULT 0.00,
total_consumption DECIMAL(10,2) DEFAULT 0.00,
last_recharge_time DATETIME,
created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES user(user_id)
);
通过balance字段实时反映用户余额,total_recharge和total_consumption实现数据统计,所有金额操作均通过数据库事务保证原子性。
核心业务逻辑实现
1. 自行车租赁流程控制
租赁业务涉及车辆状态校验、账户余额验证、记录生成等多个关联操作。LeaseServlet通过事务控制确保业务一致性:
public class LeaseServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
int userId = Integer.parseInt(request.getParameter("userId"));
int bicycleId = Integer.parseInt(request.getParameter("bicycleId"));
int siteId = Integer.parseInt(request.getParameter("siteId"));
Connection conn = DBUtil.getConnection();
conn.setAutoCommit(false);
// 校验车辆可用性
Bicycle bicycle = bicycleDAO.getBicycleById(bicycleId);
if (!"available".equals(bicycle.getStatus())) {
throw new RuntimeException("车辆不可用");
}
// 验证用户余额
UserAccount account = accountDAO.getAccountByUserId(userId);
if (account.getBalance().compareTo(new BigDecimal("5.00")) < 0) {
throw new RuntimeException("余额不足,请先充值");
}
// 生成租赁记录
LeaseRecord record = new LeaseRecord();
record.setUserId(userId);
record.setBicycleId(bicycleId);
record.setLeaseTime(new Date());
record.setLeaseSiteId(siteId);
record.setPaymentStatus("pending");
leaseRecordDAO.insert(record);
// 更新车辆状态
bicycleDAO.updateStatus(bicycleId, "rented");
conn.commit();
request.setAttribute("success", "租赁成功");
} catch (Exception e) {
conn.rollback();
request.setAttribute("error", e.getMessage());
}
}
}

2. 智能计费与支付系统
还车时系统自动计算费用并完成扣款,计费规则支持按时间阶梯计价:
public class BillingService {
public BigDecimal calculateCost(Date leaseTime, Date returnTime) {
long minutes = (returnTime.getTime() - leaseTime.getTime()) / (60 * 1000);
BigDecimal cost = BigDecimal.ZERO;
if (minutes <= 30) {
cost = new BigDecimal("1.00");
} else if (minutes <= 60) {
cost = new BigDecimal("2.00");
} else {
// 超过1小时后按每小时1元计费
long hours = minutes / 60;
cost = new BigDecimal("2.00").add(
new BigDecimal(hours - 1).multiply(new BigDecimal("1.00"))
);
}
return cost;
}
public boolean processPayment(int userId, BigDecimal amount) {
try {
UserAccount account = accountDAO.getAccountByUserId(userId);
if (account.getBalance().compareTo(amount) >= 0) {
BigDecimal newBalance = account.getBalance().subtract(amount);
accountDAO.updateBalance(userId, newBalance);
ConsumptionRecord consumption = new ConsumptionRecord();
consumption.setUserId(userId);
consumption.setAmount(amount);
consumption.setType("lease");
consumptionRecordDAO.insert(consumption);
return true;
}
return false;
} catch (SQLException e) {
return false;
}
}
}

3. 多角色权限管理系统
系统支持管理员、站点管理员、普通用户三级权限体系,通过Filter实现统一的访问控制:
@WebFilter("/*")
public class AuthFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String path = req.getRequestURI().substring(req.getContextPath().length());
// 公开路径允许直接访问
if (path.startsWith("/public") || path.equals("/login")) {
chain.doFilter(request, response);
return;
}
HttpSession session = req.getSession(false);
if (session == null || session.getAttribute("user") == null) {
res.sendRedirect(req.getContextPath() + "/login");
return;
}
User user = (User) session.getAttribute("user");
// 基于角色校验访问权限
if (path.startsWith("/admin") && !"admin".equals(user.getRole())) {
res.sendError(403, "权限不足");
return;
}
chain.doFilter(request, response);
}
}

4. 车辆调度与运维管理
站点管理员通过可视化界面监控车辆状态,系统提供智能调度建议:
public class MaintenanceService {
public List<Bicycle> getMaintenanceDueBicycles() {
String sql = "SELECT * FROM bicycle WHERE last_maintenance_date < ? OR " +
"last_maintenance_date IS NULL";
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -6); // 6个月未维护的车辆
return bicycleDAO.query(sql, new Date(cal.getTimeInMillis()));
}
public void scheduleMaintenance(int bicycleId, int siteId) {
bicycleDAO.updateStatus(bicycleId, "maintenance");
MaintenanceRecord record = new MaintenanceRecord();
record.setBicycleId(bicycleId);
record.setSiteId(siteId);
record.setScheduledTime(new Date());
record.setStatus("scheduled");
maintenanceDAO.insert(record);
}
}

实体模型与业务对象设计
系统核心实体模型采用面向对象设计,每个业务对象都封装了完整的行为方法:
public class Bicycle {
private Integer bicycleId;
private String bicycleNumber;
private Integer typeId;
private Integer siteId;
private String status;
private Date purchaseDate;
private Date lastMaintenanceDate;
public boolean isAvailable() {
return "available".equals(status);
}
public boolean needsMaintenance() {
if (lastMaintenanceDate == null) return true;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -6);
return lastMaintenanceDate.before(cal.getTime());
}
}
public class User {
private Integer userId;
private String username;
private String password;
private String role;
private String campusCard;
private String phone;
private Date registerTime;
public boolean canRentBicycle() {
// 验证用户是否有未支付订单等限制条件
return true;
}
}
数据访问层优化策略
采用连接池技术和预处理语句提升数据库访问性能:
public class DBUtil {
private static DataSource dataSource;
static {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/bike_rental");
} catch (NamingException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
public abstract class BaseDAO<T> {
protected List<T> query(String sql, Object... params) {
List<T> list = new ArrayList<>();
try (Connection conn = DBUtil.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql)) {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
}
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(convertToEntity(rs));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
protected abstract T convertToEntity(ResultSet rs) throws SQLException;
}
系统优化与功能扩展方向
移动端适配与微信小程序集成
- 开发响应式前端界面,适配手机浏览器
- 集成微信小程序SDK,实现扫码租车功能
- 利用地理位置API实现车辆实时定位
智能调度算法优化
- 基于历史数据预测各站点车辆需求峰值
- 开发路径优化算法指导车辆调度路线
- 实现供需失衡自动预警机制
物联网设备集成
- 对接智能锁硬件,实现远程开锁功能
- 集成车辆传感器,实时监测车辆健康状况
- 通过GPS模块实现电子围栏管理
大数据分析平台
- 构建用户行为分析模型,优化车辆分布
- 实现骑行热力图可视化展示
- 开发预测性维护提醒系统
微服务架构重构
- 将单体应用拆分为用户服务、车辆服务、支付服务等微服务
- 引入Spring Cloud生态体系实现服务治理
- 采用Docker容器化部署提高运维效率
该系统通过严谨的架构设计和精细的业务实现,为校园短途出行提供了完整的数字化解决方案。基于JSP+Servlet的技术选型确保了系统的稳定性和可维护性,模块化的设计为后续功能扩展奠定了坚实基础。随着校园智慧化建设的深入推进,该系统有望成为校园交通数字化基础设施的重要组成部分。