加载freemarker文件

本文介绍如何使用Freemarker模板引擎将数据填充到模板中并生成字符串。通过具体步骤展示了创建Configuration对象、设置模板路径、加载模板、准备数据集及输出处理等过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public String getContext(List<AgentBalanceInfo> agentBalanceInfoList) throws TemplateException, IOException {

String bufferString = null;

// 第一步:创建一个Configuration对象,直接new一个对象。构造方法的参数就是freemarker对于的版本号。

        Configuration configuration = new Configuration(Configuration.getVersion());

        // 第二步:设置模板文件所在的路径。

        String fileUrl = this.getClass().getClassLoader().getResource("ftl").getPath();

        configuration.setDirectoryForTemplateLoading(new File(fileUrl));

        // 第三步:设置模板文件使用的字符集。一般就是utf-8.

        configuration.setDefaultEncoding("utf-8");

        // 第四步:加载一个模板,创建一个模板对象。

        Template template = configuration.getTemplate("email.ftl");

        // 第五步:创建一个模板使用的数据集,可以是pojo也可以是map。一般是Map。

        Map<String,Object> dataModel = sendExcelMail(agentBalanceInfoList);;

        //向数据集中添加数据

//        dataModel.put("model", "hello word");

        

        // 第六步:创建一个Writer对象,一般创建一FileWriter对象,指定生成的文件名。

        Writer out = new StringWriter();

        // 第七步:调用模板对象的process方法输出文件。

        template.process(dataModel, out);

        bufferString = out.toString();

        // 第八步:关闭流。

        out.close();

return bufferString;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值