此问题出现在spring boot项目中
重点在后面最后面
问题1:ognl.OperatorAaccess找不到
这个问题就是缺少ognl依赖,在thymeleaf依赖中默认是有的,但是在spring boot 项目中引入的是spring-boot-starter-thymeleaf,其中没有包含ognl,引入ognl即可;
<!-- https://mvnrepository.com/artifact/ognl/ognl -->
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2.15</version>
</dependency>
问题2:各种模板路径解析错误TemplateInputException:template parsing…
spring boot 项目中使用的是自动注入的springTemplateEngine对象调用process():
@Resource
SpringTemplateEngine springTemplateEngine;
.........
springTemplateEngine.process("模板",context,fileWriterWithEncoding);
请认准SpringTemplateEngine而不是new 的TemplateEngine,否则执行process()会各种路径错误;并且用SpringTemplateEngine的时候用不着Resolver解析器;
完整配置
- 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.2.15</version>
</dependency>
- yaml配置
spring:
thymeleaf:
mode: HTML5
encoding: UTF-8
cache: false
prefix: classpath:/templates/
suffix: .html
- 实现方法
//创建静态页面
//1.注入模板引擎
@Resource
SpringTemplateEngine springTemplateEngine;
@GetMapping("/createStaticHtml")
public Result createStaticHtml() throws IOException {
//2.获取需要组装的动态数据,放到context对象中,这个context是Thymeleaf中的Context对象
List<Map<String, Object>> dataList = xxx.getxxxList();
Context context = new Context();
context.setVariable("list",dataList);
//创建输出流,将组装好的模板输出到指定位置;可以创建FileWriter对象(字符流),
// 但是需要指定字符集的话,就需要创建字节流FileWriterWithEncoding对象,可以使用指定的字符集转换字符输出的编码方式
//3.1指定文件输出路径
String path = this.getClass().getResource("/templates/").getPath()+"index.html";
//3.2创建可编码转换的字符输出流
FileWriterWithEncoding fileWriterWithEncoding =
new FileWriterWithEncoding(path,StandardCharsets.UTF_8);
//4.执行模板生成操作
springTemplateEngine.process("index/index",context,fileWriterWithEncoding);
//5.返回执行状态
return "ok";
}