1. 概述
本文將探討 Spring MVC 提供的核心接口 <em org.springframework.ui.Model</em>, <em org.springframework.ui.ModelMap</em> 和 <em org.springframework.web.servlet.ModelAndView</em> 的使用。
2. Maven 依賴
讓我們從我們的 pom.xml 文件中開始使用 spring-boot-starter-web 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.0.2</version>
</dependency>最新版本的 spring-boot-starter-web 依賴包可以在這裏找到:這裏。
如果使用 Thymeleaf 作為我們的視圖引擎,則應將以下依賴添加到 pom.xml 中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>3.0.2</version>
</dependency>最新版本的 Thymeleaf 依賴可以在這裏找到:這裏。
3. 模型
讓我們從這裏最基本的概念開始——模型。
簡單來説,模型可以提供用於渲染視圖的屬性。
為了為視圖提供可用的數據,我們只需將此數據添加到其模型對象中。 此外,包含屬性的映射可以與模型實例合併:
@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
與上述Model接口一樣,ModelMap也用於將值傳遞給渲染視圖。
ModelMap的優勢在於它允許我們傳遞一組值,並將這些值視為位於Map中的值:
@GetMapping("/printViewPage")
public String passParametersWithModelMap(ModelMap map) {
map.addAttribute("welcomeMessage", "welcome");
map.addAttribute("message", "Baeldung");
return "view/viewPage";
}5. ModelAndView
最終用於將值傳遞給視圖的接口是ModelAndView。
該接口允許我們以一個返回中傳遞 Spring MVC 所需的所有信息:
@GetMapping("/goToViewPage")
public ModelAndView passParametersWithModelAndView() {
ModelAndView modelAndView = new ModelAndView("view/viewPage");
modelAndView.addObject("message", "Baeldung");
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 : <span th:text="${message}"></span></div>
</body>
</html>此處傳遞的參數通過語法 ${message} 使用,這種語法被稱為佔位符。 Thymeleaf 模板引擎會將此佔位符替換為模型中同名的屬性的值。
7. 結論
在本快速教程中,我們探討了 Spring Boot 與 Spring MVC 中的三個核心概念:模型(Model)、ModelMap 和 ModelAndView。我們還查看了視圖如何利用這些值的一些示例。