- 引入Starter
<!-- 我的springboot版本2.1.2.RELEASE,对应thymeleaf3.0.11.RELEASE-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.12</version>
</dependency>
- 在resources/templates 目录下创建静态页面模板,如下
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<div>
<h2 th:text="${hello}"></h2>
</div>
</body>
</html>
- java代码
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("templates/");
resolver.setSuffix(".html");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(resolver);
FileWriter writer = new FileWriter("F:/learn/index.html");
Context context = new Context();
context.setVariable("hello",msg);
templateEngine.process("text",context,writer);