How to reset a @ModelAttribute in Spring MVC after it has been processed in the controller?

HHWilchevsky picture HHWilchevsky · Jul 29, 2011 · Viewed 15.3k times · Source

I have defined a @ModelAttribute("mymodel")

@ModelAttribute("mymodel")
MyModel mymodel() {
  MyModel mymodel = new MyModel();
  return mymodel;
 }


@RequestMapping(value = "/save", method = RequestMethod.POST)
public final void save(@ModelAttribute("mymodel") MyModel mymodel, 
                           final BindingResult binding,
    final HttpServletRequest request, 
    final ModelMap modelMap) throws Exception {
    modelService.save(mymodel);

            // try to reset the model --> doesn't work!!!
    myModel = new MyModel();
}

The problem is, even though I reset the model in the save method, if I reload the page after a save operation and save a second time, the model contains all of the values of the previous myModel.

How do I reset it after it has been processed?

Answer

Russell picture Russell · Jul 29, 2011

Unless I miss my guess, this is because

myModel = new MyModel();

is only going to reset the reference within the method, in the same way that getting a MyModel from a List<MyModel> and then calling myModel = new MyModel(); would not change the element in the List, only your local reference.

You most likely need to put the new MyModel() into the model or modelMap.

The redirect after post pattern may also be useful to you here. Have your POST method

return "redirect:originalpage.htm"

This should reload the original page fresh, and will also mean that if you hit refresh you won't resubmit the POST, saving your object twice.