Flat Preloader Icon

Spring MVC Model Interface

  • In Spring MVC, the Model interface is part of the Spring Web framework and is used to pass data from a controller to a view. The Model interface provides a way to add attributes (data) that can be accessed in the view for rendering dynamic content. It is typically used in conjunction with the ModelAndView class or as a method parameter in a controller method.
Here’s how you can use the Model interface in a Spring MVC application:

Using Model in a Controller Method

  • You can use the Model interface as a parameter in your controller method to add attributes that you want to make available to the view.
public class MyController {

    public String myPage
    (Model model) {
// Adding attributes to the model
"Hello, Spring MVC!");
model.addAttribute("count", 42);

// Return the view name
        return "myPage"; 
// The view resolver will 
resolve this to the 
actual view file (e.g., myPage.jsp)

  • In the example above, we’ve added two attributes, “message” and “count,” to the Model object. These attributes can be accessed in the associated view.

Accessing Model Attributes in a View (JSP Example)

  • Once you’ve added attributes to the Model object in your controller, you can access them in the view using expression language (EL) or JSTL tags.
  • Here’s an example using JSP:
					<!DOCTYPE html>
    <title>My Page</title>
    <p>Count: ${count}</p>

  • In the JSP view, ${message} and ${count} are placeholders for the attributes added to the Model in the controller. The values of these attributes will be rendered in the HTML when the view is displayed.

Using ModelAndView with Model'

  • In some cases, you might want to return both a view name and model attributes from a controller method. You can achieve this by using the ModelAndView class, which combines both the view name and the Model object.
public class MyController {

    public ModelAndView myPage() {
ModelAndView modelAndView 
= new ModelAndView("myPage"); 
// View name
"Hello, Spring MVC!");
// Model attribute
modelAndView.addObject("count", 42); 
// Model attribute

return modelAndView;

  • In this example, we create a ModelAndView object, set the view name, and then add model attributes using the addObject method.
  • Using the Model interface in Spring MVC allows you to pass data from the controller to the view, making it possible to render dynamic content in your web applications.