1、引入依赖
<dependency> <groupId>net.sourceforge.nekohtml</groupId> <artifactId>nekohtml</artifactId> <version>1.9.22</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>ognl</groupId> <artifactId>ognl</artifactId> <version>3.2.1</version> </dependency>
2、配置文件 .yml
spring: thymeleaf: encoding: UTF-8 cache: false # 检查模板是否存在,然后再呈现 check-template-location: true prefix: classpath:/word/ suffix: .html mode: LEGACYHTML5 servlet: content-type: text/html
3代码
private final static TemplateEngine engine = new TemplateEngine();
@Override public void AISave(String materialCarBatchId, String compilationTemplateId, HttpServletResponse response) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put("title", "测试"); Context context = new Context(); context.setVariables(dataMap); String html = engine.process("<p th:text='${title}'></p>", context); }
注意
如果引入下面的则只能根据2配置文件查找到项目内的模板
@Autowired private SpringTemplateEngine templateEngine;
Context context = new Context(Locale.getDefault(), dataMap);
String html = templateEngine.process("test.html", context);
附上 test.html 代码
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> <p th:text="${title}">${title}</p> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr>
<!-- 遍历list <tr th:each="u : ${archiveCarDetailList}"> <td th:text="${u.title}"></td> <td th:text="${u.title}"></td> <td th:text="${u.title}"></td> </tr>-->
</table> </body> </html>