ModelAndView

 

In Spring, ModelAndView is like a combined package that helps you send both data and the view (page) name from your controller to the front end. It wraps together:

  1. The View Name: The name of the page (like homePage) where you want to display the data.
  2. The Model Data: The data you want to send to that page.

How It Works:

  1. Creating ModelAndView: You create an object of ModelAndView in your controller.
  2. Setting the View: You set the page name (view) you want to display using setViewName().
  3. Adding Data: You add data using addObject(), which works like addAttribute() in Model.

Example:

Let's say you want to display a welcome message on a page called welcomePage.

In the Controller:


In the HTML (welcomePage.html):


Here, ModelAndView wraps both the view name (welcomePage) and data (message). So, when the page loads, it knows both which page to show and what data to display, making it easier to manage both in one place.



Comments