【问题标题】:NullPointerException and SQLNonTransientConnectionException when refreshing webpage刷新网页时出现 NullPointerException 和 SQLNonTransientConnectionException
【发布时间】:2022-01-25 19:25:20
【问题描述】:

我使用 Spring 和 Thymeleaf 来显示我的数据库中有多少用户,代码如下所示

    public long countUsers() {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    Long userCount = 0L;
    try {
        connection = ConnectionPool.getConnectionPool().getConnection();
        statement = connection.prepareStatement(GET_USER_COUNT);
        resultSet = statement.executeQuery();
        resultSet.next();
        userCount = resultSet.getLong("rowcount");
    } catch (SQLException e) {
        LOGGER.error(e);
    } finally {
        closeResource.close(statement);
        closeResource.close(resultSet);
        closeResource.close(connection);
        ConnectionPool.getConnectionPool().releaseConnection(connection);
    }
    return userCount;
}

这很好用,我将它显示在网页上,例如“总共有 X 个用户”,但是当我在一秒钟内刷新页面 3 次时,计数变为 0 并且它停止工作。我收到这些消息

java.sql.SQLNonTransientConnectionException: No operations allowed after connection closed.

 java.lang.NullPointerException: Cannot invoke "java.lang.AutoCloseable.close()" because "resource" is null

我正在使用控制器来计算我想要计数的位置

    @GetMapping("/")
public String homepage(Model model) {
    UserService userService = new UserService();
    model.addAttribute("userCount", userService.countUsers());
    return "index";
}

HTML 看起来像

  <div>
    <p>There are a total of <span th:text="${userCount}"></span> users created</p>
  </div>

【问题讨论】:

标签: spring-boot nullpointerexception thymeleaf


【解决方案1】:

我知道出了什么问题。我正在关闭连接,然后将其添加回ArrayBlockingQueue

当我停止关闭连接并开始将其释放回List 时,它起作用了!

感谢 cmets 帮助我走向正确的道路。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 2020-08-10
    • 1970-01-01
    • 2013-01-25
    • 2020-08-14
    • 2021-07-08
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多