4

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";
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
neeraj simon
  • 59
  • 1
  • 1
  • 5

3 Answers3

10

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

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
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");
}
Evil Toad
  • 3,053
  • 2
  • 19
  • 28
2

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.

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152