I've seen examples where a controller returns a String (which indicates the view)
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner"
}
And I also see examples where a controller returns a "ModelAndView" object type
public ModelAndView helloWorld() {
ModelAndView mav = new ModelAndView();
mav.setViewName("helloWorld");
mav.addObject("message", "Hello World!");
return mav;
}
What is the difference between the two and which should I use? Cause either way I can get my view resolved.
If we are talking about MVC 3, than, both are correct. But directly returning ModelAndView is the old way, and more verbal.
If you are returning just a string (without @ResponseBody which is something else), this string is treated as view name, and spring pushes it to view resolvers - so, you dont have to worry (at least, while you are writing controllers), what type of view renderer you'll use (let it be jsp or velocity, it doesn't matter). You only propagate the Model
instance, and returnes a hint what to do with it next. Proper ModelAndView
object is made later internally by string.
Generally, spring 3 gives you more flexibility with arguments and return types (see Defining @RequestMapping handler methods section in Spring documentaton).