When to use ModelAndView vs Model in Spring?

This may sound silly to Spring experts, but I have to ask:
How do you decide when to use ModelAndView and when to use Model ?

After all I researched, the best answer I found is this one . He mentioned that ModelAndView is the old way, and Model with String returned is the new way in Spring .

My question is, should we have a ModelAndView from the old ModelAndView now that we have the Model in hand? Or are there any cases where you need to use ModelAndView for this?

Also, does anyone know why it is necessary to change ModelAndView to Model and String as a View , and what are the benefits?

+51
java spring spring-mvc
Jun 05 '13 at 23:41
source share
4 answers

I always use an approach in which controller methods return ModelAndView . Just because it usually makes controller methods a bit more concise. Method parameters are now strictly input . And all the associated output data is contained in the object returned by the method.

The ModelAndView style seems to resonate with people who don't like updating the input parameters for a method. Adhering to the belief that this will be a side effect, a dangerous pattern, because you cannot reliably predict what this method will do, it can return data in the returned object, or it could update anything in any of the input arguments .

So, some people still prefer ModelAndView .

New style with Model as a method parameter and return string as the name of the view. This seems to come from a slightly different design approach. Here, model objects are considered a type of event or element that is passed to several handlers before returning to the view where they are displayed. It reminds me of how events are handled in the AWT / Swing world. This model is more consistent with an approach in which several handlers can be built on top of Model objects until a view is reached.

Thus, at the end of the day, there seems to be no definite reason to criticize or promote any approach. You should use a style that more closely matches your overall design philosophy.

Hope this helps.

+44
Jun 06 '13 at 10:41
source share

One difference that I can notice is the ModelAndView object, which you can set directly to the view object:

 ModelAndView mav = ... mav.setView(myView); 

While if you use Model and String, to resolve the view name into the actual view, you need a resolving view.

 public String myHandler(...) { return "myviewname"; // has to have a resolver from "myviewname" into an actual view } 
+15
Jun 06 '13 at 0:56
source share

SEO perspective. We can use ModelAndView to apply 301 redirects if we have any requirements for this. We cannot achieve this with a model.

0
Mar 16 '17 at 7:01
source share
 @RequestMapping("/") public ModelAndView AWBCOntroller() { log.info("Tracking info"); ModelAndView mav = new ModelAndView(); mav.setViewName("index"); return mav; } 
0
May 25 '19 at 6:58
source share



All Articles