Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelMap usage in Spring

What are the benifits of using ModelMap instead of a simple Map in Spring MVC. I see in the code implementation that they put the datatype of the attribute added in the map as key instead to be made available on the form.

Can anyone explain with an example.

like image 635
Anna Avatar asked May 25 '10 07:05

Anna


People also ask

What is the difference between ModelMap and ModelAndView in Spring?

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 we use ModelAndView in Spring?

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 .

When should I use ModelAndView?

I always use the approach where controller methods return ModelAndView . Simply because it tends to make the controller methods a little more terse. The method parameters are now strictly input parameters. And all output related data is contained in the object returned from the method.


1 Answers

ModelMap subclasses LinkedHashMap, and provides some additional conveniences to make it a bit easier to use by controllers

  • addAttribute can be called with just a value, and the map key is then inferred from the type.
  • The addAttribute methods all return the ModelMap, so you can chain method called together, e.g. modelMap.addAttribute('x', x).addAttribute('y',y)
  • The addAttribute methods checks that the values aren't null
  • The generic type of ModelMap is fixed at Map<String, Object>, which is the only one that makes sense for a view model.

So nothing earth-shattering, but enough to make it a bit nicer than a raw Map. Spring will let you use either one.

You can also use the Model interface, which provides nothing other than the addAttribute methods, and is implemented by the ExtendedModelMap class which itself adds further conveniences.

like image 199
skaffman Avatar answered Oct 02 '22 09:10

skaffman