'Avoid Spring MVC form resubmission when refreshing the page
I am using spring MVC to save the data into database. Problem is it's resubmitting the JSP page when I am refreshing the page. Below is my code snippet
<c:url var="addNumbers" value="/addNumbers" ></c:url>
<form:form action="${addNumbers}" commandName="AddNumber" id="form1">
</<form:form>
@RequestMapping(value = "/addNumbers", method = RequestMethod.POST)
public String addCategory(@ModelAttribute("addnum") AddNumber num){
this.numSrevice.AddNumbers(num);
return "number";
}
Solution 1:[1]
You have to implement Post/Redirect/Get.
Once the POST method is completed instead of returning a view name send a redirect request using "redirect:<pageurl>".
@RequestMapping(value = "/addNumbers", method = RequestMethod.POST)
public String addCategory(@ModelAttribute("addnum") AddNumber num){
this.numSrevice.AddNumbers(num);
return "redirect:/number";
}
And and have a method with method = RequestMethod.GET there return the view name.
@RequestMapping(value = "/number", method = RequestMethod.GET)
public String category(){
return "number";
}
So the post method will give a redirect response to the browser then the browser will fetch the redirect url using get method since resubmission is avoided
Note: I'm assuming that you don't have any @RequestMapping at controller level. If so append that mapping before /numbers in redirect:/numbers
Solution 2:[2]
You can return a RedirectView from the handler method, initialized with the URL:
@RequestMapping(value = "/addNumbers", method = RequestMethod.POST)
public View addCategory(@ModelAttribute("addnum") AddNumber num,
HttpServletRequest request){
this.numSrevice.AddNumbers(num);
String contextPath = request.getContextPath();
return new RedirectView(contextPath + "/number");
}
Solution 3:[3]
My answer shows how to do this, including validation error messages.
Another option is to use Spring Web Flow, which can do this automatically for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Evil Toad |
| Solution 3 | Neil McGuigan |
