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?
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.
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);
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With