java解析freemarker文件或模板内容

java解析freemarker文件或模板内容

freemarker文件一般是控制器返回后有freemarker控制器进行解析,在这里我们在java代码中解析freemarker文件
其他依赖包
网盘地址 提取码:i6o7


package com.my.utils;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.IOUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;

public final class FreemarkerParseUtils {
   
   /**
    * 不可实例化
    */
   private FreemarkerParseUtils () {
   }

   /**
    * 把ftl文件解析成html字符串内容
    * @param templatePath ftl文件路径
    * @param model        模型数据
    * @return 解析后的html文件内容
    */
   public static String parse(String templatePath, Map<String, Object> model) {
       StringWriter stringWriter = null;
       BufferedWriter writer = null;
       try {
           freemarker.template.Template template = SpringUtils.getBean("freeMarkerConfigurer", FreeMarkerConfigurer.class).getConfiguration().getTemplate(templatePath);
           stringWriter = new StringWriter();
           writer = new BufferedWriter(stringWriter);
           template.process(model, writer);
           writer.flush();
           return stringWriter.toString();
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           IOUtils.closeQuietly(writer);
           IOUtils.closeQuietly(stringWriter);
       }
       return null;
   }

   /**
    * 解析ftl文件内容
    * @param content  原ftl模板文件内容
    * @param model 模板文件数据
    * @return 解析后的html文件内容
    */
   public static String parseFtlContent(String content, Map<String, Object> model) {
       // 获取配置
       StringWriter out = new StringWriter();
       try {
           new Template("template", new StringReader(content), FreemarkerUtils.getFreeMarkerConfigurer().getConfiguration()).process(model, out);
       } catch (TemplateException | IOException e) {
           return "";
       }
       String htmlContent = out.toString();

       if (out != null) {
           try {
               out.close();
           } catch (IOException e) {
               return "";
           }
       }
       return htmlContent;
   }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值