Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent duplicate entries while refreshing?

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?

like image 749
Abubakkar Avatar asked Oct 04 '12 09:10

Abubakkar


People also ask

How do you prevent duplicate data entry?

Select the entire column where you need to avoid duplicates. Click on the first cell with data keeping the Shift keyboard button pressed and then select the last cell. Or simply use the combination of Ctrl + Shift + End.


2 Answers

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);
}
like image 100
BalusC Avatar answered Nov 14 '22 22:11

BalusC


I would add an invisible ID to the page. If the data is new to the database (ID = unknown), insert and create an ID and update the page with the ID. That way you know if it is a ID != unknown, and you don't have to do an insert. And if the data hasn't changed, you don't even have to do an update...

like image 21
Fildor Avatar answered Nov 14 '22 21:11

Fildor