Intellij Idea Thymeleaf不显示HTML页面中的数据

5w9g7ksd  于 2024-01-05  发布在  其他
关注(0)|答案(2)|浏览(174)

我只是在学习Thymeleaf,我不明白为什么我不能在html代码中显示数据。我的Thymeleaf控制器如下:

  1. @Controller
  2. public class UserController {
  3. @GetMapping("/index")
  4. public String getMessage(Model model) {
  5. model.addAttribute("welcome", "Hello!");
  6. return "index";
  7. }
  8. }

字符串
在我的index.html中,我有这样的东西:

  1. <div>
  2. <p th:text="${welcome}"></p>
  3. </div>


pom.xml文件中的依赖关系如下:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-devtools</artifactId>
  9. <scope>runtime</scope>
  10. <optional>true</optional>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-tomcat</artifactId>
  15. <scope>provided</scope>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.boot</groupId>
  19. <artifactId>spring-boot-starter-test</artifactId>
  20. <scope>test</scope>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.postgresql</groupId>
  24. <artifactId>postgresql</artifactId>
  25. <version>42.5.0</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  30. </dependency>
  31. </dependencies>


最后,我的“资源”文件夹的结构如下:

  1. resources
  2. |
  3. |--- css
  4. |--- img
  5. |--- js
  6. |--- login.html
  7. |---templates
  8. |
  9. |--- index.html


如果有帮助的话,我正在“macos索诺马14.2”系统上使用SpringBoot 3.2.0,并且我通过添加“Spring Bot Dev-tool”和“Spring Web”创建了我的项目。最后,我可以指定通过Postman发出Get请求可以完美地工作,它会返回带有添加消息的html页面。当我以intellij启动页面时不会发生这种情况。感谢所有帮助我的人!

ht4b089n

ht4b089n1#

代码是好的,这也是为什么 Postman 显示您正确的模板页面内容。
当你在IntelliJ“浏览器”中渲染HTML时,它不会在服务器上渲染它,Thymeleaf引擎也不会从模型中设置数据,它只是一个预览。
只需通过普通浏览器查询控制器。

tuwxkamq

tuwxkamq2#

  1. @Controller
  2. public class UserController {
  3. @GetMapping("/index")
  4. public String getMessage() {
  5. Resource resource = new ClassPathResource(templates/index.html);
  6. String htmlContent = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
  7. htmlContent = htmlContent.replace("{{welcome}}", "Hello");
  8. return htmlContent;
  9. }
  10. }

字符串
同时更新Index.html

  1. <div>
  2. <p th:text="{{welcome}}"></p>
  3. </div>


替换为以下代码

展开查看全部

相关问题