创建一个web项目,引入jar包
<properties> <org.thymeleaf.version>3.0.11.RELEASE</org.thymeleaf.version> <junit.verison>4.12</junit.verison> </properties> <dependencies> <!-- 配置thymeleaf依赖 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>${org.thymeleaf.version}</version> </dependency> <!-- 配置junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.verison}</version> <scope>test</scope> </dependency> </dependencies>
目录结构如下:
hello.html代码(该文件为主要输出文件,与thymeleaf模板代码中的hello对应,不区分大小写)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf</title>
<script type="text/javascript">
</script>
</head>
<body>
<div th:text="${message}"></div>
<!-- 引入片段 -->
<div th:include="comment::footer"></div>
</body>
</html>
comment.html(该文件为其他文件,展示thymeleaf标签里的引用代码片段功能,我试了下也可以整个文件引用过去,好像没什么问题)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>片段</title>
<script type="text/javascript">
</script>
</head>
<body>
<!-- 定义footer片段 -->
<div th:fragment="footer">
<h1>底部片段</h1>
</div>
</body>
</html>
Thymeleaf模板代码
package com.st;
import org.junit.Test;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import java.io.FileWriter;
/**
* Created with IntelliJ IDEA.
*
* @Description: 模板引擎调用
* @author: ST
* @Date: 2021-04-27
* @Time: 1:33
*/
public class ThymeleafTest {
@Test
public void testThymeleaf() throws Exception{
// 创建类路径模板解析器
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
// 设置前缀
resolver.setPrefix("/templates/");
// 设置后缀
resolver.setSuffix(".html");
// 设置模板类型
resolver.setTemplateMode(TemplateMode.HTML);
// 设置模板编码
resolver.setCharacterEncoding("UTF-8");
// 创建模板引擎
TemplateEngine engine = new TemplateEngine();
// 为引擎设置模板解析器
engine.setTemplateResolver(resolver);
// 创建上下文对象
Context context = new Context();
// 数据存放在上下文对象中,携带返回前端
context.setVariable("message", "总会有互相奔赴的爱情!");
// 模板引擎处理模板,输出文件
// String template resources下的模板,通过文件名进行匹配,不区分大小写
// IContext context 模板引擎
// Writer writer 输出
// 这里是通过模板引擎直接输出到指定绝对路径下的指定HTML文件中
engine.process("hello", context,
new FileWriter("C:\\Users\\ST\\Desktop\\hello.html"));
}
}
效果展示