Deep Analysis of the Model Mechanism in ModelAndView from Spring MVC

Dec 11, 2025 · Programming · 12 views · 7.8

Keywords: Spring MVC | ModelAndView | Model Mechanism

Abstract: This article provides an in-depth exploration of the Model component in Spring MVC's ModelAndView class, explaining its role in data transfer between controllers and views. Through analysis of ModelAndView constructor parameters, model attribute setting methods, and EL expression usage in JSP views, it clarifies how Model serves as a data container for passing business logic results to the presentation layer. Code examples demonstrate different handling approaches for string and object-type model attributes, while comparing multiple ModelAndView initialization methods to help developers fully understand Spring MVC's model-view separation architecture.

Overview of the Model Component in ModelAndView

In the Spring MVC framework, ModelAndView is a core class that encapsulates view names and model data, used by controllers to pass information to the view layer after request processing. The Model component serves as a data container, responsible for carrying business data that needs to be displayed in the view.

Basic Working Principle of Model

When a controller method returns a ModelAndView object, the Spring MVC framework extracts the model data and passes it as request attributes to the view resolver. In view technologies like JSP, these model attributes can be accessed through Expression Language (EL).

Consider the following typical example:

protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
    String message = "Welcome to our website!";
    return new ModelAndView("welcomePage", "WelcomeMessage", message);
}

In this example, the ModelAndView constructor accepts three parameters: the view name "welcomePage", the model attribute name "WelcomeMessage", and the model attribute value message. The model attribute name serves as the key and the attribute value as the value, added to the model map.

Types and Usage of Model Attributes

Model attributes can be simple types (such as strings or numbers) or complex objects. Different types of attributes are accessed differently in views.

Example of String-Type Model Attribute:

Controller code:

return new ModelAndView("welcomePage", "WelcomeMessage", "Welcome!");

Corresponding JSP view code:

<p>Hello! ${WelcomeMessage}</p>

This renders as: <p>Hello! Welcome!</p>

Example of Object-Type Model Attribute:

First, define a simple JavaBean:

public class UserBean {
    private String name;
    private String greeting;
    
    // Constructors, getters, and setters omitted
}

Controller code:

UserBean user = new UserBean();
user.setName("Mike");
user.setGreeting("Hello!");

return new ModelAndView("welcomePage", "user", user);

Corresponding JSP view code:

<p>${user.greeting} ${user.name}</p>

This renders as: <p>Hello! Mike</p>

Alternative Construction Methods for ModelAndView

Besides using the three-parameter constructor, ModelAndView objects can also be created by explicitly setting the view name and adding model attributes. This approach provides clearer code structure, making it easier to understand the separation between model and view.

The following code demonstrates this alternative method:

ModelAndView mav = new ModelAndView();
mav.setViewName("welcomePage");
mav.addObject("WelcomeMessage", message);
return mav;

This method is functionally equivalent to using the constructor directly, but through explicit method calls, it more clearly demonstrates the two independent operations of setting the view name and adding model attributes.

Role of Model in View Resolution

After the ModelAndView object is returned, Spring MVC's view resolver, based on configuration, resolves the view name into a specific view implementation (such as a JSP file). Model data is automatically added to request attributes, allowing the view to access them via EL expressions.

For example, if the view resolver is configured to resolve "welcomePage" to /WEB-INF/views/welcomePage.jsp, then when this JSP file is rendered, all model attributes added via the addObject method are available as variables in EL expressions.

Scope and Lifecycle of Model Attributes

By default, model attributes added through ModelAndView have request scope, meaning they are only valid during the current request processing cycle. This design aligns with the stateless nature of web applications, ensuring data isolation between different requests.

If data needs to persist across requests, developers might consider using session scope or application scope, but this typically requires other mechanisms (such as the @SessionAttributes annotation) rather than directly through ModelAndView.

Best Practices and Considerations

When using the Model component of ModelAndView, it is recommended to follow these best practices:

  1. Choose meaningful names for model attributes to improve code readability
  2. Avoid adding excessive data to the model; only pass information necessary for view rendering
  3. For complex objects, ensure appropriate getter methods are implemented to allow property access in EL expressions
  4. Consider using ModelMap or the Model interface as controller method parameters, which can provide more flexible model manipulation in certain scenarios

By properly utilizing the Model component, developers can build clear, maintainable Spring MVC applications, achieving effective separation between business logic and presentation logic.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.