Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between ModelAndView and ModelMap? [duplicate]

Is ModelMap just the new name in Spring 3 for a ModelAndView?

Does the functionality change in Spring 3?

Consider this code in a Spring 3 app using a ModelMap:

 @RequestMapping(value = "/order", method = RequestMethod.GET)
 public final String setup(final ModelMap model)
 {
  model.addAttribute(ORDER, new Order());
  return "setup";
 }

I would like to know what the equivalent use here of ModelAndView would be in an older Spring app? Would it just require a name change from ModelMap to ModelAndView to get this working in Spring 2.5?

like image 470
pnut butter Avatar asked Jul 27 '10 14:07

pnut butter


People also ask

What is differences between model ModelMap and ModelAndView?

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.

Why do we use ModelMap?

ModelMap is an extension of Model with the ability to store attributes in a map and chain method calls. ModelAndView is a holder for a model and a view; it allows to return both model and view in one return value.

What is 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 use of @ModelAttribute?

@ModelAttribute is an annotation that binds a method parameter or method return value to a named model attribute, and then exposes it to a web view. In this tutorial, we'll demonstrate the usability and functionality of this annotation through a common concept, a form submitted from a company's employee.


2 Answers

ModelAndView, as its name suggests, contains the model, and the name of the view. ModelMap, in contract, only contains information about the model.

Your example would have been written (in "old" Spring) as

 public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
 {
  return new ModelAndView("setup", ORDER, new Order());
 }
like image 126
skaffman Avatar answered Sep 30 '22 20:09

skaffman


@coder247 Someone correct me if I'm wrong, but you don't need to return a ModelMap. Add your attributes to your ModelMap and simply return a String which is the View name.

This is an excellent article that explains how to do this and more... http://www.mkyong.com/spring-mvc/spring-mvc-form-handling-annotation-example/

like image 27
Rob Breidecker Avatar answered Sep 30 '22 22:09

Rob Breidecker