Spring Web MVC – The ModelAndView Object

In this tutorial, you will learn how to pass information from your Controller class to the View using the Spring MVC ModelAndView object.

In previous lessons, we discussed how to use Model and ModelMap for the same purpose – to pass properties from Controller to the View.  The ModelAndView class, you will also use to pass attributes from Controller to the view, but it is used slightly differently.

ModelAndView class is a holder object for both Model and View.

package com.appsdeveloperblog.tutorials.spring.mvc.estore;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Controller
public class HomeController {

    @GetMapping("/")
    public ModelAndView homePage() {

        Map<String, String> model = new HashMap<>();
        model.put("firstName", "Sergey");
        model.put("lastName", "Kargopolov");

        ModelAndView modelAndView = new ModelAndView("home", model);

        return modelAndView;
    }

}

Because ModelAndView object already contains both the view name and the model, our method, will need to return an object of ModelAndView class, instead of a view name.

The AddObjects() Method

The ModelAndView class also supports an alternative way of adding attributes. To add attributes we can use the addObject() method.

ModelAndView modelAndView = new ModelAndView("home");

modelAndView.addObject("firstName", "Sergey");
modelAndView.addObject("lastName", "Kargopolov");

Display Attributes in the View

In the View, we can access and display attributes from the ModelMap object using the ${attributeName}.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<p th:text="'Hello ' + ${firstName} + ' ' + ${lastName}" />

</body>
</html>

I hope this tutorial was helpful for you. To learn more about building Web applications with Spring Framework, please visit the Spring Web MVC category.  You will find many useful tutorials there.

Happy learning!


Leave a Reply

Your email address will not be published. Required fields are marked *