【问题标题】:Why does JSP duplicate records on the client-side when refreshed?为什么 JSP 在刷新时会在客户端重复记录?
【发布时间】:2020-04-23 10:38:19
【问题描述】:

我的 JSP 页面在刷新时复制了它在客户端显示的记录。我尝试了另一个具有相同过程的项目,但效果很好。这是页面的截图。 Image

这是我在欢迎文件(控制器)中的代码

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    List<Todo> todos = null;
    try {
        todos = todoDaoImpl.getTodos();
        request.setAttribute("todo_list", todos);
        request.getRequestDispatcher("views/list-todo.jsp").forward(request, response);
    } catch (Exception e) {
        logger.warning("Error in list todo");
    }
}

JSP 代码

<table class="table table-striped">
  <caption>Your Todos are:</caption>
  <tr>
    <th id="desc">Description</th>
    <th id="category">Category</th>
    <th id="action">Action</th>
  </tr>

  <tbody>
    <c:forEach items="${todo_list}" var="todo">
      <tr>
        <td>${todo.todos}</td>
        <td>${todo.category}</td>
        <td><a href="${loadTodoLink}" class="btn btn-primary">Update</a>
          <a class="btn btn-danger" href="${deleteLink}" onclick="if(!(confirm('Do you want to delete this?'))) return false">Delete</a></td>
      </tr>
    </c:forEach>
  </tbody>
</table>

DAO 代码

List<Todo> todos = new ArrayList<>();

@Override
public List < Todo > getTodos() throws Exception {
    String sql = "SELECT * from todo";

    try (Connection conn = dataSource.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql);
            ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            int id = rs.getInt("id");
            String todo = rs.getString("todo");
            String category = rs.getString("category");

            todos.add(new Todo(id, todo, category));
        }
        return todos;
    }
}

【问题讨论】:

    标签: jsp


    【解决方案1】:

    在你的 DAO 代码中,你有这个:todos.add(new Todo(id, todo, category));

    每次您点击getTodos() 方法时,您都会添加到列表中。

    要么将todos 列表作为方法的一部分(而不是声明为全局变量),要么在填充之前在getTodos() 方法中清除它。

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 2015-09-10
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      相关资源
      最近更新 更多