我正在研究 Thymeleaf,我不明白为什么我无法在 html 代码中显示数据。 我的 Thymeleaf 控制器如下:
@Controller
public class UserController {
@GetMapping("/index")
public String getMessage(Model model) {
model.addAttribute("welcome", "Hello!");
return "index";
}
}
在我的index.html 中我有这样的内容:
<div>
<p th:text="${welcome}"></p>
</div>
pom.xml文件中的依赖如下:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
最后我的“resources”文件夹的结构如下:
resources
|
|--- css
|--- img
|--- js
|--- login.html
|---templates
|
|--- index.html
如果有帮助的话,我正在“macos Sonoma 14.2”系统上使用 SpringBoot 3.2.0,并通过添加“Spring Bot Dev-tool”和“Spring Web”创建了我的项目。最后,我可以指定通过 Postman 发出 Get 请求效果很好,它返回带有添加消息的 html 页面。当我以 intellij 身份启动页面时,不会发生这种情况。感谢所有帮助我的人!
代码没问题。
当您在 IntelliJ“浏览器”中渲染 HTML 时,它不会在服务器上渲染它,并且 Thymeleaf 引擎不会设置模型中的数据,这只是预览。