In Java, POST
-REDIRECT-GET
pattern is used to avoid resubmission of the same data by refreshing the page by the user. Consider a situation in which a user submits his data but does not receive any response of success or a new page. He refreshes the page, which causes the resubmission of the same form, causing the submission of the same data. This can be avoided by implementing the POST
-REDIRECT-GET
pattern.
POST
-REDIRECT-GET
patternIn the POST
-REDIRECT-GET
pattern, the post request at form submission is redirected towards the get request, which avoids the resubmission of the same data on refresh.
Here is an example of a Spring Boot project using this pattern:
In the example, there is a controller productController.java
for handling product requests. It contains two GET
requests and one POST
request. /products
is for getting all products and /addProduct
is for displaying form page. The post request /product
is actually implementing the PRG pattern for adding products. It adds products and then redirects the request to server which then gets the product_details
page. Click the "Run" button to run the application:
package com.educative.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AppApplication { public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } }
Here is the improved explanation of the key code lines in ProductsController.java
:
Lines 21–25: Defines a GET
request handler that retrieves all products and displays them on the product_details
page.
Lines 27–30: Handles a GET
request to serve the product_form
page, allowing users to add a new product.
Lines 32–37: Processes a POST
request by adding a new product to the list and then redirects to a GET
request that displays the updated list of all products.
The usage of the POST
-REDIRECT-GET
pattern is a recommended practice that will improve the dependability of Web interactions on posts to eliminate the problem of double submission. In this approach, user inputs are processed safely and results can be shown without problems even the browser page is refreshed. The user interactions go to this method as it enables applications to offer a better and more uniform experience, removing frustration and potential mistakes due to numerous data submissions. This pattern proves to be especially useful in situations where the information has to be especially clean and the interface has to be particularly engaging.
Free Resources