This might sound dumb to the Spring
experts, but I have to ask:
How do you decide on when to use ModelAndView
and when to use Model
?
After all I have researched the best answer I have found is this one. It has mentioned that the ModelAndView
is an old way and the Model
with a String
returned is a new way in Spring
.
My question is shall we deprecate the old ModelAndView
now that we have Model
in hand? Or is there any cases that you need to use ModelAndView
for it?
Also, does anyone know why the have to change ModelAndView
to Model
and String
value as View
, and what are the benefits?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments