Spring Web MVC – The ModelMap Object

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

To make ModelMap object available to your controller, you will simply inject it as an argument to your method. Just the same way as we have injected, the Model object in the previous video lesson.

@Controller
public class HomeController {

    @GetMapping("/")
    public String homePage(ModelMap model) {
        // ...
        return "home";
    }
}

Adding Attributes

Let’s assume that we need to pass the user’s first name and last name from the Controller to the View. To do that, we can use the addAttribute() method that the ModelMap provides.

@Controller
public class HomeController {

    @GetMapping("/")
    public String homePage(ModelMap model) {
        model.addAttribute("firstName", "Sergey");
        model.addAttribute("lastName", "Kargopolov");
        return "home";
    }
}

Display Model 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 *