我有一个 index.jsp
页面,其中有一个表单,用户可以在其中输入一些数据,这些数据使用 Controller servlet 存储在数据库中。
我想在数据库中输入数据后显示与该表单相同的页面 (index.jsp
)。另外,我想显示用户在数据库中输入的所有条目。
我尝试使用 RequestDispatcher
的 forward()
方法。它工作正常(这意味着我能够再次显示相同的表单,并使用 JSTL 显示该用户在表单下方输入的所有数据)。
但问题是每当用户按下 Refresh 或 F5
按钮时,所有以前的数据也会输入到数据库中,当我显示所有数据时,重复的条目也会出现.
我想过使用 POST-REDIRECT-GET 模式,但问题是当我重定向时我没有使用 JSTL 显示这些数据。
我该怎么做?
最佳答案
I thought of using POST-REDIRECT-GET pattern but the problem is when I redirect I don't get those data to be displayed using JSTL.
只需发送一个请求参数以及标识您希望在新 GET 请求中显示的信息。
// ...
Long id = dataService.save(data);
// ...
response.sendRedirect(request.getContextPath() + "/index?editId=" + id);
然后在 servlet 中它映射到 /index
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Long editId = Long.valueOf(request.getParameter("editId")); // Handle nullcheck yourself.
Data editData = dataService.find(editId);
request.setAttribute("editData", editData); // For the edit form.
List<Data> allData = dataService.list();
request.setAttribute("allData", allData); // For the table/list of all data.
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
关于java - 如何在刷新时防止重复条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12724526/