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?
@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).
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.
@ModelAttribute in Depth As the introductory paragraph revealed, we can use @ModelAttribute either as a method parameter or at the method level.
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
@ModelAttribute
annotated methods@SessionAttribute
s available to the controllerIn 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With