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.
				
					@Controller
public class MyController {

    @GetMapping("/myPage")
    public String myPage
    (Model model) {
// Adding attributes to the model
model.addAttribute("message",
"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>
<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>${message}</h1>
    <p>Count: ${count}</p>
</body>
</html>

				
			
  • 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.
				
					@Controller
public class MyController {

    @GetMapping("/myPage")
    public ModelAndView myPage() {
ModelAndView modelAndView 
= new ModelAndView("myPage"); 
// View name
modelAndView.addObject("message",
"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.