Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC: Passing a Model as an argument to a controller method VS instantiating it explicitly

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?

like image 801
AtomHeartFather Avatar asked Oct 01 '14 17:10

AtomHeartFather


People also ask

What is the difference between @RequestParam and ModelAttribute?

@ModelAttribute and @RequestParam both interrogate the request parameters for information, but they use this information differently: @RequestParam just populates stand-alone variables (which may of course be fields in a @ModelAttribute class).

What is the difference between ModelMap and ModelAndView in Spring?

Q : What is the difference between ModelMap and ModelAndView? Model is an interface while ModelMap is a class. ModelAndView is just a container for both a ModelMap and a View object. It allows a controller to return both as a single value.

Can we use @ModelAttribute as a method argument?

@ModelAttribute in Depth As the introductory paragraph revealed, we can use @ModelAttribute either as a method parameter or at the method level.


1 Answers

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.

like image 74
M. Deinum Avatar answered Oct 01 '22 23:10

M. Deinum