我正在使用 Thymeleaf 模板引擎来显示来自 Java 21 后端的一些信息。由于某些莫名其妙的原因,th:text 属性值没有显示在 html 页面上。非 thymeleaf 纯 HTML 显示正确。
我的控制器文件(TemplateController.java):
package com.example.demo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class TemplateController {
@GetMapping("/")
public String template (Model model) {
String msg = "Hello World";
//adding the attribute(key-value pair)
model.addAttribute("message", msg);
//returning the view name
return "index";
}
}
====================================================== ============
我的index.html文件:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org", lang="en">
<head>
<title>Image and Text</title>
<meta name="viewport", content="width=device-width, initial-scale=1.0", charset=UTF-8 />
<link rel="stylesheet" type="text/css" media="all" th:href="@{/css/style.css}" />
</head>
<body>
<h1> Welcome to Geeks Geeks...</h1>
<div id="one">
<h1 th:text="${message}"></h1>
</div>
</body>
</html>
====================================================== ========= 我的 pol.xml 包含 spring-boot-starter-thymeleaf 依赖项:
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
...
====================================================== ========= 控制器文件(TemplateController.java)位于 src/main/java/com/example/demo/
index.html位于src/main/resources/templates/下
我在 VS Code 中有“Live Server”扩展。当我使用 Live Server 打开时,我只能看到我的 HTML 代码。我没有看到 Thymeleaf 模板化的任何内容。
我尝试更改 TemplateController.java 和 index.html 中的 attributeName
model.addAttribute("msg1", msg);
但这没有什么区别。
我尝试直接写入消息字符串,但也没有什么区别。
model.addAttribute("message", "Hello World");
linting、安全代码扫描或 Duet AI 没有捕获任何错误。 Maven 构建成功。
这看起来很基本,但我不知道出了什么问题。谁能发现为什么 Thymeleaf 不显示属性值?
index.html 文件中存在语法错误,请尝试删除某些标签属性之间所需的所有位置
,
:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<title>Image and Text</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" charset=UTF-8 />
<link rel="stylesheet" type="text/css" media="all" th:href="@{/css/style.css}" />
</head>
<body>
<h1> Welcome to Geeks Geeks...</h1>
<div id="one">
<h1 th:text="${message}"></h1>
</div>
</body>
</html>