7

I have created two test methods in my MVC Controller class. In the first method the Model is being passed as an argument and in the second one I instantiate it directly. In both methods I add a single attribute to the Model instance:

@RequestMapping("/test-modelParam")
public String testMethod1(Model model) {
    model.addAttribute("testname", "testvalue");
    return "/testview";
}


@RequestMapping("/test-modelInstantiatedExplicitly")
public ModelAndView testMethod2() {
    ModelAndView mav = new ModelAndView("/testview");
    mav.addObject("testname", "testvalue");
    return mav;
}

The View gets populated correctly in both cases.

Is there any difference between the two approaches? If so, Where is it preferred to use one over the other?

AtomHeartFather
  • 954
  • 17
  • 35
  • 1
    In the end no there isn't. However the `Model` gets pre-populated with some values (especially if you use path variables) whereas the second doesn't. Also returning a `String` instead of a `ModelAndView` is a lot easier. – M. Deinum Oct 01 '14 at 17:37
  • Possible duplicate of http://stackoverflow.com/questions/7175509/which-is-better-return-modelandview-or-string-on-spring3-controller and http://stackoverflow.com/questions/16951609/when-to-use-modelandview-vs-model-in-spring – DolphinJava Oct 01 '14 at 19:10
  • @M.Deinum thanks; So, what kind of values is the ``Model`` pre-populated with when not using path variables? – AtomHeartFather Oct 01 '14 at 22:58
  • @DolphinJava I don't think this is a duplicate. The questions you linked seem more about differences between ``Model`` and ``ModelAndView``. Good reading though :-) – AtomHeartFather Oct 01 '14 at 23:00
  • When using flash attributes those are added, when using `@SessionAttributes` those should be also available. Results of methods annotated with `@ModelAttribute` are also there. It basically is the pre populated model. – M. Deinum Oct 02 '14 at 05:43
  • Additional note the Model is always created and merged with the one you add/create with `ModelAndView` or when using data binding the `BindingResult`. So it will always be there but you can choose to receive it or not. – M. Deinum Oct 02 '14 at 06:08
  • @M.Deinum thanks, that makes sense. Would you be able to point me to the documentation that covers that? Also, if you want to post that as an answer, please do and I will accept. Cheers. – AtomHeartFather Oct 08 '14 at 15:10

1 Answers1

8

In the end there is no difference everything will end up in a ModelAndView eventually.

When using the Model or ModelMap as a method argument it will get pre-populated with some values

  1. Path Variables
  2. Result of any @ModelAttribute annotated methods
  3. Any @SessionAttributes available to the controller

In short it is the pre-populated model made available to the method.

The Model is always created and is merged with the one you add/create with a ModelAndView.

M. Deinum
  • 115,695
  • 22
  • 220
  • 224