Junior — Middle
What is the difference between ModelMap and ModelAndView objects in the context of data transfer in Spring MVC?
sobes.tech AI
Answer from AI
In Spring MVC, the objects ModelMap and ModelAndView are used to pass data from the controller to the view, but they have different purposes:
-
ModelMap is simply a container for model attributes (key-value pairs) that can be passed to a controller method. It is used for adding data that will be accessible in the view.
-
ModelAndView is a more complex object that contains both the model (data) and the view name. It is used when you need to specify what data to pass and which view to display.
Example:
@RequestMapping("/example")
public ModelAndView example() {
ModelAndView mav = new ModelAndView("viewName");
mav.addObject("message", "Hello World");
return mav;
}
// or with ModelMap
@RequestMapping("/example2")
public String example2(ModelMap model) {
model.addAttribute("message", "Hello World");
return "viewName";
}
Thus, ModelMap is convenient for simple data addition, while ModelAndView provides more explicit control over both the model and the view.