FreeMarker代码生成原理

依赖

 <!-- FreeMarker -->
 <dependency>
     <groupId>org.freemarker</groupId>
     <artifactId>freemarker</artifactId>
     <version>2.3.31</version>
 </dependency>

工具类:FreemarkerUtil.java

 import freemarker.template.Configuration;
 import freemarker.template.Template;
 import freemarker.template.TemplateException;
 ​
 import java.io.File;
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.Writer;
 import java.util.Map;
 ​
 /**
  * @description FreeMarker代码生成工具类
  */
 public class FreemarkerUtil {
     /**
      * 根据模板,利用提供的数据,生成文件
      *
      * @param ftlNameWithPath 模板文件路径
      * @param data            数据
      * @param aimFileName     最终生成的文件路径
      * @throws IOException
      * @throws TemplateException
      */
     public static void execute(String ftlNameWithPath, Map<String, Object> data, String aimFileName) throws IOException, TemplateException {
         //创建Freemarker配置实例
         Configuration cfg = new Configuration(Configuration.VERSION_2_3_25);
 ​
         int i = ftlNameWithPath.lastIndexOf("/") == -1 ? ftlNameWithPath.lastIndexOf("\\") : ftlNameWithPath.lastIndexOf("/");
 ​
         cfg.setDirectoryForTemplateLoading(new File(ftlNameWithPath.substring(0, i + 1)));
 ​
         cfg.setDefaultEncoding("UTF-8");
         //加载模板文件
         Template t1 = cfg.getTemplate(ftlNameWithPath.substring(i + 1));
         Writer out = new FileWriter(new File(aimFileName));
         t1.process(data, out);
         out.flush();
         out.close();
     }
 }

测试模板:index.ftl

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>${titleName}的主页</title>
 </head>
 <body>
 <h3>欢迎访问${userName}的主页</h3>
 ${msg}
 </body>
 </html>

代码生成:CodeGenerator.java

 import freemarker.template.TemplateException;
 ​
 import java.io.IOException;
 import java.util.HashMap;
 import java.util.Map;
 ​
 /**
  * @description 代码生成
  */
 public class CodeGenerator {
     public static void main(String[] args) throws TemplateException, IOException {
         Map<String, Object> map = new HashMap<>();
         map.put("titleName", "JngKang");
         map.put("userName", "JngKang");
         map.put("msg", "JngKang的主页");
         // 模板文件路径
         String ftlNameWithPath = "D:\\Code\\Study\\CodeTestDemo\\src\\main\\java\\test\\index.ftl";
         // 生成文件路径
         String aimFileName = "JngKangIndex.html";
         FreemarkerUtil.execute(ftlNameWithPath, map, aimFileName);
     }
 }

生成结果:index.html

 <!DOCTYPE html>
 <html lang="en">
 <head>
     <meta charset="UTF-8">
     <title>JngKang的主页</title>
 </head>
 <body>
 <h3>欢迎访问JngKang的主页</h3>
 JngKang的主页
 </body>
 </html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值