Thymeleaf生成静态页面报错,ognl.OperatorAaccess找不到,将模板路径识别成模板,模板路径解析错误TemplateInputException:template parsi

此问题出现在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解析器;

完整配置

  1. 引入依赖
<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>
  1. yaml配置
 spring:
  thymeleaf:
    mode: HTML5
    encoding: UTF-8
    cache: false
    prefix: classpath:/templates/
    suffix: .html
  1. 实现方法
//创建静态页面
//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";
}

重点来了,新手求赞💪

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值