When to use ModelAndView vs Model in Spring?
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.
The ModelAndView
style seems to resonate with people who don't like updating input parameters to a method. Sticking to the belief that this would constitute a side effect, a dangerous pattern because you cannot reliably predict what the method is going to do - It could return data in the returned object, or it could have updated anything in any of the input arguments.
So some people will still continue to prefer ModelAndView
.
The new style with Model
as method parameter and returned string as view name. Seems to have come from a slightly different design approach. Here the model objects are considered to be sort of events or items that are passed to multiple handlers, before being returned to the view where they are rendered. It reminds me how events are handled in the AWT / Swing world. This model is more coherent with the approach where multiple handlers could build on top of the Model
objects, till it reaches a view.
So at the end of the day, there does not seem to be a definite reason to criticise or promote either approach. You should use the style that feels more consistent to your overall design philosophy.
Hope this helps.
One difference I can spot is with ModelAndView object you can set a direct reference to a view object:
ModelAndView mav = ...
mav.setView(myView);
Whereas if you use Model and String, you need a view resolver to resolve the view name into an actual view
public String myHandler(...) {
return "myviewname"; // has to have a resolver from "myviewname" into an actual view
}