Passing Data Using Model, ModelMap, and ModelAndView in Spring MVC
Course: Advanced Java Training
Topic: Passing Data Using Model, ModelMap, and ModelAndView
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Homepage
1. Introduction to Passing Data in Spring MVC
In Spring MVC, controllers handle incoming HTTP requests and prepare the data required by the application's view. A view may be a JSP page, Thymeleaf template, or another supported view technology. To display dynamic information, the controller must pass data to the view.
Spring MVC provides several approaches for sharing data between controllers and views. Three commonly used options are Model, ModelMap, and ModelAndView.
- Model: An interface that provides methods to add attributes to the model.
- ModelMap: A map-based class used to store model attributes as key-value pairs.
- ModelAndView: An object that holds both the view information and the model data.
These approaches are primarily used when a controller returns a view for rendering. For REST APIs, developers commonly return response objects through @RestController or @ResponseBody instead.
2. Understanding the MVC Data Flow
Spring MVC follows the Model-View-Controller design pattern. Each component has a specific responsibility.
| Component |
Responsibility |
Example |
| Model |
Holds data that the view needs to display. |
Student name, course title, product price. |
| View |
Displays data to the user. |
JSP or Thymeleaf template. |
| Controller |
Handles requests, prepares model data, and selects a view. |
A controller method returning "student". |
| DispatcherServlet |
Receives requests and coordinates Spring MVC request processing. |
Routes a request to the appropriate handler. |
Example of the Request Flow
- A user opens
/student in a browser.
- Spring MVC maps the request to a controller method.
- The controller retrieves or prepares student information.
- The controller adds the information to the model using
Model, ModelMap, or ModelAndView.
- Spring resolves the selected view.
- The view reads the model attributes and displays the data.
3. Passing Data Using the Model Interface
The Model interface is a common and straightforward way to pass data from a controller to a view. It provides methods such as addAttribute() and addAllAttributes().
When a controller method accepts a Model parameter, Spring provides the model object for that request. You can add attributes to it and return a view name as a string.
Example: Using Model in a Controller
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class StudentController {
@GetMapping("/student")
public String showStudent(Model model) {
model.addAttribute("studentName", "Rahul");
model.addAttribute("studentAge", 22);
model.addAttribute("courseName", "Advanced Java");
return "student";
}
}
Explanation:
@Controller marks the class as a Spring MVC controller.
@GetMapping("/student") maps HTTP GET requests to the URL /student.
Model model allows the method to add attributes for the view.
addAttribute("studentName", "Rahul") stores a value under the key studentName.
return "student" asks Spring MVC to resolve the view named student.
Accessing Model Data in a Thymeleaf View
If the application uses Thymeleaf, the view may be stored at src/main/resources/templates/student.html.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Student Details</title>
</head>
<body>
<h1>Student Details</h1>
<p>Name: <span th:text="${studentName}"></span></p>
<p>Age: <span th:text="${studentAge}"></span></p>
<p>Course: <span th:text="${courseName}"></span></p>
</body>
</html>
The expressions such as ${studentName} read the corresponding model attributes when the template is rendered.
Common Model Methods
| Method |
Purpose |
addAttribute(String name, Object value) |
Adds an attribute using a specified name and value. |
addAttribute(Object value) |
Adds an attribute using a name inferred from the object type when possible. |
addAllAttributes(Map<String, ?> attributes) |
Adds attributes from a map. |
mergeAttributes(Map<String, ?> attributes) |
Adds attributes without replacing existing attributes with the same names. |
containsAttribute(String name) |
Checks whether the model contains an attribute. |
4. Passing Multiple Values Using Model
A controller can add several independent values to the model. This is useful when a view needs a page title, a username, a list of courses, or other information.
import java.util.Arrays;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class CourseController {
@GetMapping("/courses")
public String showCourses(Model model) {
List<String> courses = Arrays.asList(
"Advanced Java",
"Spring Boot",
"Hibernate"
);
model.addAttribute("pageTitle", "Available Courses");
model.addAttribute("courses", courses);
return "courses";
}
}
In a Thymeleaf template, a list can be displayed using iteration:
<h1 th:text="${pageTitle}"></h1>
<ul>
<li th:each="course : ${courses}"
th:text="${course}"></li>
</ul>
This approach keeps the controller responsible for preparing data while the template is responsible for displaying it.
5. Passing Data Using ModelMap
ModelMap is a map-based class that Spring MVC provides for storing model attributes. Its values are organized as key-value pairs, much like a Java map. It can be used as a controller method parameter to add data for the view.
Example: Using ModelMap
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class EmployeeController {
@GetMapping("/employee")
public String showEmployee(ModelMap modelMap) {
modelMap.addAttribute("employeeName", "Priya");
modelMap.addAttribute("employeeId", 101);
modelMap.addAttribute("department", "IT");
return "employee";
}
}
Explanation:
ModelMap stores data using attribute names and values.
addAttribute() adds each value to the model.
- The returned string identifies the view that should display the data.
- The view can access the values using expressions such as
${employeeName}.
Using ModelMap in a Thymeleaf Template
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Employee Details</title>
</head>
<body>
<h1>Employee Information</h1>
<p>Name: <span th:text="${employeeName}"></span></p>
<p>Employee ID: <span th:text="${employeeId}"></span></p>
<p>Department: <span th:text="${department}"></span></p>
</body>
</html>
ModelMap Methods
| Method |
Description |
addAttribute(name, value) |
Adds an attribute to the model map. |
addAllAttributes(map) |
Adds all entries from another map. |
mergeAttributes(map) |
Adds entries while preserving existing attributes with matching keys. |
containsAttribute(name) |
Checks whether an attribute exists. |
get(name) |
Retrieves a value using its key. |
6. Passing Data Using ModelAndView
ModelAndView combines the view selection and model data into a single object. Instead of returning only a view name and using a separate model parameter, the controller creates a ModelAndView, sets its view, adds attributes, and returns the object.
Example: Using ModelAndView
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ProductController {
@GetMapping("/product")
public ModelAndView showProduct() {
ModelAndView mav = new ModelAndView("product");
mav.addObject("productName", "Laptop");
mav.addObject("productPrice", 65000);
mav.addObject("productCategory", "Electronics");
return mav;
}
}
Explanation:
new ModelAndView("product") sets the view name to product.
addObject() adds attributes to the model contained in the object.
- The method returns both the view information and the model data together.
- Spring resolves the view and makes the attributes available to the template.
Alternative Ways to Configure ModelAndView
ModelAndView mav = new ModelAndView();
mav.setViewName("product");
mav.addObject("productName", "Laptop");
You can also set a view object directly when the application uses a configured view implementation. For most simple applications, specifying a view name is sufficient.
Important ModelAndView Methods
| Method |
Purpose |
addObject(name, value) |
Adds a model attribute. |
setViewName(name) |
Sets the view name. |
getViewName() |
Returns the configured view name, if present. |
getModel() |
Returns the model map. |
setStatus(status) |
Sets the HTTP status for the response when supported by the configured handling flow. |
7. Difference Between Model, ModelMap, and ModelAndView
| Feature |
Model |
ModelMap |
ModelAndView |
| Type |
Interface |
Map-based class |
Class holding view and model information |
| Main purpose |
Pass data to a view |
Pass data through a map-like API |
Return view information and data together |
| Typical method |
addAttribute() |
addAttribute() |
addObject() |
| View selection |
Usually returned separately as a string |
Usually returned separately as a string |
Can be specified within the object |
| Typical return value |
String |
String |
ModelAndView |
| Common use |
Simple MVC controller methods |
Controllers that prefer map-style model access |
Methods that package view and model together |
All three approaches can pass model attributes to a view. The choice depends on coding style and whether keeping the view selection alongside the model data is useful.
8. Complete Example: Student Management Page
The following example demonstrates a student details page using Model. The same data could be passed with ModelMap or ModelAndView.
Controller
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class StudentDetailsController {
@GetMapping("/student-details")
public String studentDetails(Model model) {
model.addAttribute("name", "Amit Sharma");
model.addAttribute("course", "Advanced Java");
model.addAttribute("duration", "4 Months");
model.addAttribute("status", "In Progress");
return "student-details";
}
}
Thymeleaf View
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Student Details</title>
</head>
<body>
<h1>Student Details</h1>
<p>Name: <span th:text="${name}"></span></p>
<p>Course: <span th:text="${course}"></span></p>
<p>Duration: <span th:text="${duration}"></span></p>
<p>Status: <span th:text="${status}"></span></p>
</body>
</html>
When a user visits /student-details, the controller prepares the four attributes and returns the view name. Thymeleaf renders those values in the HTML response.
9. Common Mistakes and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Model value does not appear |
The attribute name in the template differs from the controller key. |
Check spelling and letter case in both places. |
| View cannot be found |
The view name or template location is incorrect. |
Verify the template filename and view resolver configuration. |
| ModelAndView returns an unexpected result |
The view name is missing or incorrectly configured. |
Set the view name or provide a valid view object. |
| Null value appears in the page |
The controller did not add the expected attribute or its value is null. |
Check the controller logic and data retrieval. |
| Collection is not displayed |
The template uses the wrong collection name or iteration expression. |
Verify the model key and template iteration syntax. |
| Changes do not appear after submission |
The controller redirects or returns a different view than expected. |
Inspect the request flow and determine which model is available to the destination view. |
10. Best Practices for Passing Data
- Use meaningful and consistent attribute names.
- Choose
Model for straightforward controller-to-view data transfer.
- Use
ModelMap when a map-style API is more convenient for the implementation.
- Use
ModelAndView when returning the view and model together improves clarity.
- Keep business logic in service classes rather than controller methods.
- Pass only the data needed by the view instead of exposing unnecessary internal objects.
- Use DTOs when preparing structured page data or handling form submissions.
- Validate user input and handle errors explicitly.
- Do not treat model attributes as persistent storage; they are normally associated with the current request.
- Use redirect attributes or other appropriate mechanisms when data must be carried through a redirect.
- For REST APIs, return suitable response objects and status codes rather than view names when a template is not intended.
11. Practice Exercises
- Create a controller that sends a username and email address to a Thymeleaf view using
Model.
- Create a product listing page that passes a list of products using
ModelMap.
- Create a course details page using
ModelAndView, including course title, duration, and fee.
- Modify a controller to pass a list of student names and display them in an HTML list.
- Intentionally misspell a model attribute name and observe how the view behaves.
- Create a service class that retrieves course details and pass the resulting data to a view.
12. Interview Questions and Answers
Q1. What is the purpose of the Model interface in Spring MVC?
The Model interface stores attributes that a controller makes available to a view for rendering.
Q2. What is ModelMap?
ModelMap is a map-based class used to store model attributes as key-value pairs.
Q3. What is ModelAndView?
ModelAndView holds both view information and model data so a controller can return them together.
Q4. Can Model and ModelMap perform similar tasks?
Yes. Both can be used to add attributes to the model. They differ mainly in their API and underlying type.
Q5. How does a Thymeleaf page access model attributes?
A Thymeleaf template can access an attribute using an expression such as ${studentName}, provided the controller has added that attribute to the model.
Q6. Is model data stored permanently?
No. Model attributes are normally intended for rendering the current request. They are not a replacement for a database or persistent storage.
Q7. Can ModelAndView be used with REST APIs?
It is primarily designed for MVC view rendering. REST APIs generally use @RestController, response objects, and HTTP message converters.
Q8. What happens if a controller returns a view name without adding model attributes?
The view can still render, but any expected dynamic values that were not supplied may be absent or null, depending on the template and expression.
13. Quick Revision
- Model: An interface for adding attributes to the model.
- ModelMap: A map-based class for storing model attributes.
- ModelAndView: Combines view information and model data.
- Model attribute: A named value available to a view during rendering.
- View name: A logical name resolved to a template or view.
- Thymeleaf expression:
${attributeName} accesses model data in a template.
- Important distinction: Model data is not automatically persistent and is not a substitute for a database.
14. Conclusion
Passing data using Model, ModelMap, and ModelAndView is an essential concept in Spring MVC. These mechanisms allow controllers to prepare application data and make it available to JSP, Thymeleaf, and other supported views.
Use Model for simple and readable controller methods, ModelMap when a map-style API is convenient, and ModelAndView when you want to package view information and model attributes into one return object. Practice all three approaches to understand how Spring MVC separates request handling, data preparation, and presentation.
Explore Advanced Java Training: View the Advanced Java Training Course
Register for a Demo: Register for a Course Demo
Visit JustAcademy: JustAcademy Homepage