Is it better to use ModelAndView or return a String as a view?

Viewed 1099

I'm building a Spring MVC application and just wondering what the convention is concerning modeling and view.

Is it better to return a ModelAndView or just return a view name as a string?

Example

public ModelAndView showInformation(){
 ModelAndView myMV= new ModelAndView("display-information");
 myMV.addObject("info",myObject);
 return myMV;   
}

OR

public String showInformation(Model theModel){
  theModel.addAttribute("info",myObject);
  return "display-information";
}

In my opinion, using ModelAndView makes your intentions much clearer, but it involves more setting up compared to simply returning a string.

1 Answers

ModelAndView is Model (data) + View (viewname). View name is string as it is being handled by TemplateViewResolver. Thus it make no difference if you choose to return String (viewname) and handle data using Modal. Infact returning string as view was added to Spring later thus is more advanced. But i prefer ModelAndView over returning string. Reasons are

  1. More readable as it gives clear picture of view and data i wish to return from my controller
  2. During the course of development if service call in controller breaks, i am sure that correct view is returned instead of any abrupt string being returned. thus my template resolver is always happy.
Related