Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between Model, ModelMap, and ModelAndView?

What are the main differences between the following Spring Framework classes?

  • Model
  • ModelMap
  • ModelAndView

Using Model.put(String,Object) we can access the values in .jsp files, but ModelMap.addAttribute(String,Object) also did same thing. I do not understand the difference between these classes.

like image 556
Basavaraj Avatar asked Aug 28 '13 11:08

Basavaraj


People also ask

What is a ModelAndView?

ModelAndView is a holder for both Model and View in the web MVC framework. These two classes are distinct; ModelAndView merely holds both to make it possible for a controller to return both model and view in a single return value. The view is resolved by a ViewResolver object; the model is data stored in a Map .

What is the difference between model and @ModelAttribute?

As Model needs a pair of name and value to populate, @ModelAttribute element 'value' is used as attribute name and the method returned object is used as value. If no 'value' is specified in @ModelAttribute then the returned type is used as the attribute name.

What is ModelAndView addObject?

public ModelAndView addObject(Object attributeValue) Add an attribute to the model using parameter name generation. Parameters: attributeValue - the object to add to the model (never null ) See Also: ModelMap.addAttribute(Object) , getModelMap()


2 Answers

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.

like image 156
Bart Avatar answered Oct 01 '22 03:10

Bart


Differences between Model, ModelMap, and ModelAndView

Model: It is an Interface. It defines a holder for model attributes and primarily designed for adding attributes to the model.

Example:

@RequestMapping(method = RequestMethod.GET)     public String printHello(Model model) {           model.addAttribute("message", "Hello World!!");           return "hello";        } 

ModelMap: Implementation of Map for use when building model data for use with UI tools.Supports chained calls and generation of model attribute names.

Example:

@RequestMapping("/helloworld") public String hello(ModelMap map) {     String helloWorldMessage = "Hello world!";     String welcomeMessage = "Welcome!";     map.addAttribute("helloMessage", helloWorldMessage);     map.addAttribute("welcomeMessage", welcomeMessage);     return "hello"; } 

ModelAndView: This class merely holds both to make it possible for a controller to return both model and view in a single return value.

Example:

@RequestMapping("/welcome") public ModelAndView helloWorld() {         String message = "Hello World!";         return new ModelAndView("welcome", "message", message);     } 
like image 34
Vikas Harle Avatar answered Oct 01 '22 02:10

Vikas Harle