How can I prevent duplicating data while refreshing the page in Spring

Viewed 40

In my project I have two pages first one is for entering the data and the second one is for showing the data to the user. When I refresh the result page data is dublicated. I tried to fix this but I am not familiar with PRG pattern. I want to prevent the duplication if the user refreshes the result page.

    @RequestMapping(value = { "/display-form", "mainPage.html" }, method = RequestMethod.GET)
public ModelAndView displayForm() {
    ModelAndView mv = new ModelAndView("mainPage");
    mv.addObject("formData", new SampleModel());
    
    return mv;

}

@RequestMapping(value = "/send-form-data", method = RequestMethod.POST)
public ModelAndView processForm(@Valid @ModelAttribute("formData") SampleModel formData, BindingResult res) {
    ModelAndView mv = new ModelAndView();
    fmv.validate(formData, res);
    mv.addObject("formData", formData);
    service.delete(1);
    
    if(res.hasErrors())
    {
        mv.setViewName("mainPage");
    }
    else
    {
        mv.setViewName("result");
        service.create(formData);
        mv.addObject("list", service.findAll());
    }
    return mv;

}
1 Answers

Try to create the ModelAndView instance with redirection, so that when actions completes, you get a 3xx redirection (to the initial form, for example):


ModelAndView mv = new ModelAndView("redirect:/display-form");
// .. as before ..
Related