What is Model in ModelAndView from Spring MVC?
The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.
Example 1
If you have...
return new ModelAndView("welcomePage","WelcomeMessage","Welcome!");
... then in your jsp, to display the message, you will do:-
Hello Stranger! ${WelcomeMessage} // displays Hello Stranger! Welcome!
Example 2
If you have...
MyBean bean = new MyBean();
bean.setName("Mike!");
bean.setMessage("Meow!");
return new ModelAndView("welcomePage","model",bean);
... then in your jsp, you can do:-
Hello ${model.name}! {model.message} // displays Hello Mike! Meow!
new ModelAndView("welcomePage", "WelcomeMessage", message);
is shorthand for
ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);
Looking at the code above, you can see the view name is "welcomePage". Your ViewResolver
(usually setup in .../WEB-INF/spring-servlet.xml
) will translate this into a View. The last line of the code sets an attribute in your model (addObject("WelcomeMessage", message)
). That's where the model comes into play.