Put data into the model in Spring MVC controller

In the MVC model, the controller will inject data into the model and these data will be used on the view. In this tutorial, we will learn how to put data into the model in your Spring MVC controller.

Spring MVC demonstrates very clearly the MVC model, which provides us with some objects for storing data for the model:

  • java.util.Map
  • org.springframework.ui.Model
  • org.springframework.ui.ModelMap

We only need to declare these objects as a method parameter in the Spring MVC controller. Each object has methods that allow us to add data to the model with key and value.

Use the Model object

In the previous example, the home() method used the Model object to store data for the model:

As you can see, the Model object has an addAttribute() method that is used to add data to the model. This method has two parameters with the key data type String and value data type Object.


Use the Map object

For Map object, you will probably be more familiar as it is a Java object. We can declare as follows:

Use the ModelMap object

ModelMap is the object implementing the Map interface in Java so it is similar to the Map object above. We can use the put() method of the Map object, and ModelMap supports a number of other methods to populate the model.

We can declare as follows:

Result

All of these objects give us the same result:

Put data into the model in Spring MVC controller

Đánh giá bài viết
Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment