Spring Web MVC – The Model Object

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

A Model is an object that you can use to pass attributes from the Controller to the View.

To make the Model object available to a method in your controller class, you will simply inject it as an argument to your method.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

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

}

Adding Attributes to the Model

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 Model provides.

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String homePage(Model 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 Model 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 *