1. 概述

本文将深入探讨 Spring MVC 提供的三个核心组件:org.springframework.ui.Modelorg.springframework.ui.ModelMaporg.springframework.web.servlet.ModelAndView。这些组件在视图渲染中扮演着关键角色,理解它们的区别和使用场景能帮你避免不少踩坑。

2. Maven 依赖

首先在 pom.xml 中添加核心依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>3.0.2</version>
</dependency>

最新版本可查看 这里

如果使用 Thymeleaf 作为视图引擎,还需添加:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>3.0.2</version>
</dependency>

最新版本见 这里

3. Model

Model 是最基础的数据载体,简单粗暴地用于向视图传递渲染数据。核心特点:

  • ✅ 支持添加单个属性
  • ✅ 支持合并 Map 数据
  • ❌ 本身不包含视图信息

示例代码:

@GetMapping("/showViewPage")
public String passParametersWithModel(Model model) {
    Map<String, String> map = new HashMap<>();
    map.put("spring", "mvc");
    model.addAttribute("message", "Baeldung");
    model.mergeAttributes(map);
    return "view/viewPage";
}

4. ModelMap

ModelMap 本质上是 Model 的 Map 实现版本,主要优势在于:

  • ✅ 提供类 Map 操作接口
  • ✅ 支持链式调用(虽然示例中没体现)
  • ⚠️ 与 Model 功能高度重叠,选其一即可

示例代码:

@GetMapping("/printViewPage")
public String passParametersWithModelMap(ModelMap map) {
    map.addAttribute("welcomeMessage", "welcome");
    map.addAttribute("message", "Baeldung");
    return "view/viewPage";
}

5. ModelAndView

ModelAndView 是重量级选手,特点非常鲜明:

  • ✅ 同时封装模型数据和视图信息
  • ✅ 适合需要统一处理视图和数据的场景
  • ❌ 灵活性稍低于单独使用 Model

示例代码:

@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
    ModelAndView modelAndView = new ModelAndView("view/viewPage");
    modelAndView.addObject("message", "Baeldung");
    return modelAndView;
}

6. 视图层使用

所有传递到模型的数据最终都会在视图层(如 Thymeleaf 模板)中被消费。以 Thymeleaf 为例:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Title</title>
</head>
<body>
    <div>Web Application. Passed parameter : <span th:text="${message}"></span></div>
</body>
</html>

关键点说明:

  • ${message} 是 Thymeleaf 的占位符语法
  • 引擎会自动替换为模型中同名属性的值
  • 支持复杂对象访问(如 ${user.name}

7. 总结

三种组件的核心差异总结:

组件 视图信息 数据操作方式 典型使用场景
Model 单属性/Map 简单数据传递
ModelMap Map风格 需要 Map 操作接口时
ModelAndView 对象方法 需要同时控制视图和数据时

实际开发建议:

  • 优先使用 ModelModelMap(二选一)
  • 仅在需要统一返回视图和数据时使用 ModelAndView
  • 避免在同一个项目中混用多种方式

完整示例代码可在 GitHub 获取。


原始标题:Model, ModelMap, and ModelAndView in Spring MVC