我只是在学习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
|
|--- css
|--- img
|--- js
|--- login.html
|---templates
|
|--- index.html
型
如果有帮助的话,我正在“macos索诺马14.2”系统上使用SpringBoot 3.2.0,并且我通过添加“Spring Bot Dev-tool”和“Spring Web”创建了我的项目。最后,我可以指定通过Postman发出Get请求可以完美地工作,它会返回带有添加消息的html页面。当我以intellij启动页面时不会发生这种情况。感谢所有帮助我的人!
2条答案
按热度按时间ht4b089n1#
代码是好的,这也是为什么 Postman 显示您正确的模板页面内容。
当你在IntelliJ“浏览器”中渲染HTML时,它不会在服务器上渲染它,Thymeleaf引擎也不会从模型中设置数据,它只是一个预览。
只需通过普通浏览器查询控制器。
tuwxkamq2#
字符串
同时更新Index.html
型
替换为以下代码