You need to enable JavaScript to run this app. Java Web中数据库更新后页面列表未同步,需重启应用才显示最新数据
优惠活动
大模型
产品
解决方案
定价
更多

Java Web中数据库更新后页面列表未同步,需重启应用才显示最新数据

预约管理Java Web应用数据同步异常问题

异常现象

  • 操作触发:点击CANCEL按钮执行stopReservation方法取消当前预约
  • 数据库状态:已确认对应预约的isActive字段更新成功
  • 页面表现:操作完成重定向返回的预约列表与操作前完全一致,无状态变更;仅重启整个应用后,页面才能加载到最新状态的预约数据
  • 网络请求观测:取消操作的POST请求返回302状态码,加载全量预约列表的/allreservs请求返回200状态码,但页面列表始终未更新

涉及代码实现

1. 取消预约接口Servlet

@WebServlet("/cancel")
public class CancelReservationServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/cancel.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, NumberFormatException {
        String reservId = req.getParameter("id");
        if (reservId.isEmpty()) {
            resp.sendRedirect(req.getContextPath() + "/cancel");
        } else {
            ReservationService reservationService = new ReservationService();
            try {
                reservationService.stopReservation(Integer.parseInt(reservId));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            resp.sendRedirect(req.getContextPath() + "/allreservs");
        }
    }
}

2. 全量预约列表接口Servlet

@WebServlet("/allreservs")
public class AllReservationsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ReservationService reservationService = new ReservationService();
        Set<ReservationDto> reservations = null;
        try {
            reservations = reservationService.getListOfReserves();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        req.setAttribute("reservations", reservations);
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/WEB-INF/pages/allreservs.jsp");
        requestDispatcher.forward(req, resp);
    }
}

3. Service层取消预约方法实现

public void stopReservation(Integer reservationId) throws IOException, ClassNotFoundException, SQLException {
    Connection connection = ConnectionFactory.getConnection();
    try {
        preparedStatement = connection.prepareStatement("UPDATE reservation set isActive = false where reservationId = ?");
        preparedStatement.setInt(1, reservationId);
        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

4. 全量预约列表JSP页面实现

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>All reservation</title>
    <link href="https://fonts.googleapis.com/css2?family=Baloo+Tamma+2:wght@500;600;700&display=swap" rel="stylesheet">
    <style>
        <%@include file="/styles/style.css"%>
    </style>
</head>
<body>
<p>
    <a href='<c:url value="/"/>'><- 返回主页面</a>
</p>
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>诊疗项目</th>
        <th>描述</th>
        <th>开始时间</th>
        <th>结束时间</th>
        <th>是否有效</th>
        <th>房间号</th>
        <th colspan="2">取消操作</th>
    </tr>
    </thead>
    <c:forEach items="${reservations}" var="reservations">
        <tbody>
        <tr>
            <td>${reservations.id}</td>
            <td>${reservations.fullName}</td>
            <td>${reservations.manipulationName}</td>
            <td>${reservations.description}</td>
            <td>${reservations.startTime}</td>
            <td>${reservations.endTime}</td>
            <td>${reservations.isActive}</td>
            <td>${reservations.roomNumber}</td>
            <td>
                <form action="${pageContext.request.contextPath}/cancel" method="post">
                    <td>
                        <button onclick="location.href='/cancel'">取消</button>
                        <input type="hidden" name="id" value="${reservations.id}">
                    </td>
                </form>
            </td>
        </tr>
        </tbody>
    </c:forEach>
</table>
</body>
</html>

5. 全量预约列表查询方法实现

public Set<ReservationDto> getListOfReserves() throws IOException, ClassNotFoundException, SQLException {
    Connection connection = ConnectionFactory.getConnection();
    preparedStatement = connection.prepareStatement(GET_RESERVE_DATA);
    result = preparedStatement.executeQuery();
    while (result.next()) {
        reservs.add(new ReservationDto(
                result.getInt("reservationId"),
                result.getString("fullName"),
                result.getString("manipulationName"),
                result.getString("description"),
                result.getTimestamp("startTime"),
                result.getTimestamp("endTime"),
                result.getBoolean("isActive"),
                result.getInt("roomNumber")));
    }
    return reservs;
}

private static final String GET_RESERVE_DATA = "SELECT rsrv.reservationId, CONCAT(empl.name, ' ', empl.surname) as fullname, " +
        "rsrv.manipulationName, rsrv.description, rsrv.startTime, " +
        "rsrv.endTime, rsrv.isActive, r.roomNumber, empl.employeeId, r.roomId FROM reservation AS rsrv " +
        "JOIN room as r ON rsrv.roomid = r.roomId " +
        "JOIN employee as empl ON rsrv.emplId = empl.employeeId ";

问题根因定位

  • 核心问题出在getListOfReserves方法的集合定义:代码中使用的reservs集合是类级别的成员变量,并非方法内部创建的局部变量。方法执行时不会清空原有集合内容,仅通过while循环把新查询到的记录追加到已存在的集合中,导致首次加载预约列表后,后续所有查询操作返回的都是首次加载的旧数据,与数据库最新状态无关。只有应用重启后类加载器重新初始化该集合,才能加载到最新数据,与观测到的现象完全匹配。
  • 辅助规范问题:
    1. Service层的数据库操作未遵循资源关闭规范,Connection、PreparedStatement、ResultSet对象均为类级成员变量,未在方法执行完成后关闭释放,长运行场景下会引发连接泄漏
    2. 取消按钮绑定的onclick="location.href='/cancel'"事件会打断form表单的POST提交流程,正常场景下会导致取消操作无法正确携带预约ID完成提交
    3. 数据库操作未显式管理事务提交逻辑,完全依赖连接默认的自动提交配置,在部分数据库连接池配置下会出现更新执行但未真正持久化的问题

修复方案

  1. 修改getListOfReserves方法,将集合改为方法内部创建的局部变量,每次查询时生成全新的集合承载查询结果,同时使用try-with-resources语法自动释放数据库资源:
public Set<ReservationDto> getListOfReserves() throws IOException, ClassNotFoundException, SQLException {
    // 每次查询新建集合,避免全局复用
    Set<ReservationDto> reservs = new HashSet<>();
    try (Connection connection = ConnectionFactory.getConnection();
         PreparedStatement preparedStatement = connection.prepareStatement(GET_RESERVE_DATA);
         ResultSet result = preparedStatement.executeQuery()) {
        while (result.next()) {
            reservs.add(new ReservationDto(
                    result.getInt("reservationId"),
                    result.getString("fullName"),
                    result.getString("manipulationName"),
                    result.getString("description"),
                    result.getTimestamp("startTime"),
                    result.getTimestamp("endTime"),
                    result.getBoolean("isActive"),
                    result.getInt("roomNumber")));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return reservs;
}
  1. 同步修改stopReservation方法,将数据库操作对象改为方法内局部变量,自动释放资源:
public void stopReservation(Integer reservationId) throws IOException, ClassNotFoundException, SQLException {
    try (Connection connection = ConnectionFactory.getConnection();
         PreparedStatement preparedStatement = connection.prepareStatement("UPDATE reservation set isActive = false where reservationId = ?")) {
        preparedStatement.setInt(1, reservationId);
        preparedStatement.executeUpdate();
        // 显式提交事务(适配非自动提交的连接配置)
        connection.commit();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
  1. 修改JSP页面的取消按钮逻辑,移除无效的onclick跳转代码,确保表单POST请求可以正确携带预约ID提交:
<td>
    <button type="submit">取消</button>
    <input type="hidden" name="id" value="${reservations.id}">
</td>

内容的提问来源于stack exchange,提问作者Алена Чувасова

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.29 12:24:06