Spring Boot 集成 Thymeleaf 的快速实现示例,无法渲染页面问题解决

发布于:2025-07-07 ⋅ 阅读:(14) ⋅ 点赞:(0)

以下是一个完整的 ​​Spring Boot 集成 Thymeleaf​​ 的快速实现示例,包含代码、配置和项目结构说明。所有步骤均基于最新实践整理,可直接用于开发。


1. ​​项目依赖(pom.xml)​

添加 Spring Boot Web 和 Thymeleaf 依赖:

<dependencies>
    <!-- Web 支持 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Thymeleaf 模板引擎 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <!-- 开发热更新(可选) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>


2. ​​配置文件(application.yml)​

配置模板路径、缓存等(开发阶段建议关闭缓存):

spring:
  thymeleaf:
    prefix: classpath:/templates/  # 模板存放目录
    suffix: .html                  # 文件后缀
    cache: false                   # 禁用缓存(开发环境)
    encoding: UTF-8                # 编码
    mode: HTML                     # 模板模式


3. ​​项目结构​


src/
├── main/
│   ├── java/
│   │   └── com/example/demo/
│   │       ├── DemoApplication.java   # 启动类
│   │       └── controller/
│   │           └── HelloController.java  # 控制器
│   ├── resources/
│       ├── static/    # 静态资源(CSS/JS)
│       └── templates/ # Thymeleaf 模板
│           └── hello.html


4. ​​启动类(DemoApplication.java)​

package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

5. ​​控制器(HelloController.java)​

处理请求并传递数据到模板:

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    
    @GetMapping("/hello")
    public String hello(Model model) {
        // 向模板传递数据
        model.addAttribute("name", "Thymeleaf");
        model.addAttribute("users", new String[]{"Alice", "Bob", "Charlie"});
        return "hello"; // 对应 templates/hello.html
    }
}

重点、重点、重点:

注解用@Controller ,而不是@RestController

因为@RestController包括

@Controller
@ResponseBody

会导致,页面只显示"hello",不渲染页面。

API需要返回数据类容,API要加注解@ResponseBody


6. ​​Thymeleaf 模板(hello.html)​

使用 Thymeleaf 语法渲染动态内容:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Thymeleaf Demo</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name} + '!'">默认文本(无数据时显示)</h1>
    
    <!-- 条件判断 -->
    <p th:if="${users.length > 0}">用户列表:</p>
    
    <!-- 循环遍历 -->
    <ul>
        <li th:each="user : ${users}" th:text="${user}"></li>
    </ul>
    
    <!-- 表单示例 -->
    <form th:action="@{/submit}" method="post">
        <input type="text" name="username" placeholder="输入用户名">
        <button type="submit">提交</button>
    </form>
</body>
</html>


7. ​​运行与验证​

  1. 启动 DemoApplication 主类。
  2. 访问 http://localhost:8080/hello,页面将显示:
    • 标题:Hello, Thymeleaf!
    • 用户列表:Alice、Bob、Charlie
    • 表单输入框

8. ​​关键功能说明​

​功能​ ​实现方式​
​数据绑定​ 通过 model.addAttribute("key", value) 传递数据,模板中用 ${key} 引用 
​条件渲染​ th:if / th:unless 控制元素显示 
​循环遍历​ th:each="item : ${list}" 遍历集合 
​表单绑定​ th:action="@{/url}" 和 th:field="*{fieldName}" 绑定表单数据 
​静态资源引用​ 使用 @{/path/to/resource} 引用 static/ 目录下的 CSS/JS 

扩展:表单提交处理

// 表单提交处理示例
@PostMapping("/submit")
public String submitForm(@RequestParam String username) {
    System.out.println("收到用户名:" + username);
    return "redirect:/success"; // 重定向到成功页
}