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 the .jsp files, but ModelMap.addAttribute(String,Object) did the same. I do not understand the difference between these classes.

+45
spring spring-mvc
Aug 28 '13 at 11:31
source share
3 answers

Model is the interface, and ModelMap is the class.

ModelAndView is just a container for both ModelMap and the view object. It allows the controller to return both as one value.

+53
Aug 28 '13 at 12:02
source share

Differences between Model, ModelMap and ModelAndView

Model: This is the interface. It defines a holder for model attributes and is primarily intended to add attributes to a model.

Example:

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

ModelMap: Implement a map to use when creating model data for use with user interface tools. Supports chained calls and generates 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 simply contains both to allow the controller to return both models and the view to a single return value.

Example:

 @RequestMapping("/welcome") public ModelAndView helloWorld() { String message = "Hello World!"; return new ModelAndView("welcome", "message", message); } 
+9
Jun 30 '17 at 6:38
source share

Model : This is an interface containing four addAttribute methods and one merAttribute method.

ModelMap : implements the map interface. It also contains the Map method.

ModelAndView . As Bart explains, it allows you to return the controller as a single value.

+7
Feb 24 '15 at 10:59
source share



All Articles