Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 308
neeraj simon Avatar asked Oct 25 '25 02:10

neeraj simon


2 Answers

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

like image 119
Karthikeyan Vaithilingam Avatar answered Oct 26 '25 17:10

Karthikeyan Vaithilingam


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");
}
like image 30
Evil Toad Avatar answered Oct 26 '25 16:10

Evil Toad