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";
}
You have to implement Post-Get-Redirect.
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
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");
}
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.