neeraj simon
neeraj simon

Reputation: 59

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";
}

Upvotes: 4

Views: 11721

Answers (3)

seenukarthi
seenukarthi

Reputation: 8624

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

Upvotes: 10

Neil McGuigan
Neil McGuigan

Reputation: 48246

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.

Upvotes: 2

Evil Toad
Evil Toad

Reputation: 3242

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");
}

Upvotes: 2

Related Questions