Contents

Spring MVC中的Model、ModelMap和ModelAndView

1.概述

在本文中,我们将了解Spring MVC 提供的核心org.springframework.ui.Modelorg.springframework.ui.ModelMaporg.springframework.web.servlet.ModelAndView的使用。

2.Maven依赖

让我们从pom.xml文件中的spring-context依赖项开始:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

可以在此处 找到最新版本的 spring-context 依赖项。

对于ModelAndView,需要spring-web依赖项:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>

可以在此处 找到最新版本的 spring-web 依赖项。

而且,如果我们使用 Thymeleaf 作为我们的视图,我们应该将此依赖项添加到 pom.xml:

<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11.RELEASE</version>
</dependency>

可以在这里 找到最新版本的 Thymeleaf 依赖项。

3. Model

让我们从这里最基本的概念开始——Model

简单地说,模型可以提供用于渲染视图的属性。

要为视图提供可用数据,我们只需将此数据添加到其Model对象中。此外,具有属性的地图可以与Model实例合并:

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

4. ModelMap

就像上面的Model接口一样,ModelMap也用于传递值来渲染视图。 ModelMap的优点是它使我们能够传递值的集合并将这些值视为在Map中:

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

5. ModelAndView

将值传递给视图的最终接口是ModelAndView

这个接口允许我们一次返回传递 Spring MVC 所需的所有信息:

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

6. 视图

我们放置在这些模型中的所有数据都被一个视图使用——通常是一个模板化的视图来呈现网页。

如果我们有一个 Thymeleaf 模板文件,我们的控制器方法将其作为他们的视图。可以从 thymeleaf HTML 代码中访问通过模型传递的参数:

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

此处传递的参数通过语法*${message}*使用,称为占位符。Thymeleaf 模板引擎将用通过模型传递的同名属性的实际值替换此占位符。