ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 一、Thymeleaf简介 Thymeleaf 是一个服务器端 Java 模板引擎,能够处理 HTML、XML、CSS、JAVASCRIPT 等模板文件。Thymeleaf 模板可以直接当作静态原型来使用,它主要目标是为开发者的开发工作流程带来优雅的自然模板,也是 Java 服务器端 HTML5 开发的理想选择。 ## 二、集成 使用Maven坐标将thymeleaf引入到项目中 ~~~ <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ~~~ 对thymeleaf模板进行配置 ~~~ spring: thymeleaf: cache: false # 启用缓存:建议生产开启 check-template-location: true # 检查模版是否存在 enabled: true # 是否启用 encoding: UTF-8 # 模版编码 excluded-view-names: # 应该从解析中排除的视图名称列表(用逗号分隔) mode: HTML5 # 模版模式 prefix: classpath:/templates/ # 模版存放路径 suffix: .html # 模版后缀 ~~~ ## 三、Hello ThymeLeaf 例子完成之后,项目代码结构如下: ![](https://box.kancloud.cn/f77873ca7ea16dc9523728386b9aeb0c_441x684.png) 查询一个articles文章列表,并返回模板名称,由Spring根据名称找到模板进行页面渲染 ~~~ @Controller @RequestMapping("/template") public class TemplateController { @Resource(name="articleMybatisRestServiceImpl") ArticleRestService articleRestService; @GetMapping("/thymeleaf") public String index(Model model) { List<ArticleVO> articles = articleRestService.getAll(); model.addAttribute("articles", articles); //模版名称,实际的目录为:resources/templates/thymeleaftemp.html return "thymeleaftemp"; } } ~~~ thymeleaf模板页面 ~~~ <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <meta charset="UTF-8" /> <title>thymeleaf简单示例</title> </head> <body> <h1>Hello Thymeleaf</h1> <table class=""> <tr> <td>作者</td> <td>教程名称</td> <td>内容</td> </tr> <!-- 用thymeleaf语法遍历articles列表--> <tr th:each="item : ${articles}"> <td th:text="${item.author}"></td> <td th:text="${item.title}"></td> <td th:text="${item.content}"></td> </tr> </table> <img src="/image/template.png"> </body> </html> ~~~ ## 四、访问测试 访问测试地址:[http://localhost:8888/template/freemarker](http://localhost:8888/template/freemarker) ![](https://box.kancloud.cn/5eb0da512cb55d541f99dda5d2df87e1_760x825.png)