How to prevent duplicate entries while refreshing?

Abubakkar picture Abubakkar · Oct 4, 2012 · Viewed 8.7k times · Source

I have an index.jsp page where I have a form where the user enters some data that gets stored in the database using a Controller servlet.

I want to display the same page (index.jsp) with that form after entering the data in the database. Also, I want to display all the entries that the user entered in the database.

I tried using the forward() method of RequestDispatcher. It works fine (meaning I am able to display that same form again and also display all the data entered by that user below the form using JSTL).

But the problem is whenever the user presses the Refresh or F5 button, all the previous data also gets entered in the database and as I am displaying all the data, and that duplicate entries also come up.

I thought of using the POST-REDIRECT-GET pattern, but the problem is when I redirect I don't get those data to be displayed using JSTL.

How do I do it?

Answer

BalusC picture BalusC · Oct 11, 2012

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.

Just send a request parameter along identifying the information you'd like to display in the new GET request.

// ...
Long id = dataService.save(data);
// ...
response.sendRedirect(request.getContextPath() + "/index?editId=" + id);

and then in the servlet which is mapped on an URL pattern of /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);
}