美文网首页
利用Freemarker生成静态文件

利用Freemarker生成静态文件

作者: 小程杂货铺 | 来源:发表于2017-06-21 14:13 被阅读0次

Freemarker是一个比较知名Java模版引擎,使用人数众多,今天记录下使用Freemarker来生成静态文件,主要应用场景为页面静态化以及代码生成器中

引入Maven依赖

目前最新的版本

<dependency>
       <groupId>org.freemarker</groupId>
       <artifactId>freemarker</artifactId>
       <version>2.3.26-incubating</version>
</dependency>

开始编码。

新建一个工具类,比如FreemarkerUtils,具体代码如下:

 private static Configuration cfg = null;
  /**
   * 获取Configuration对象
   */
 private Configuration getConfiguration() {
        if (null == cfg) {
            cfg = new Configuration(Configuration.VERSION_2_3_26);
            //设置模版放置路径,这里表示在classpath下的templates文件夹下
            cfg.setClassForTemplateLoading(this.getClass(), "/templates/");
            // 设置编码
            cfg.setEncoding(Locale.getDefault(), "UTF-8");
            // 设置对象的包装器
            cfg.setObjectWrapper(new DefaultObjectWrapper());
            // 设置异常处理器,否则没有的属性将会报错
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler
                                            .IGNORE_HANDLER);
        }
        return cfg;
 }

    /**
     * 生成静态文件
     * @param templatePath 模版路径
     * @param data 模版需要的数据
     * @param outputPath 输出路径
     * @return
     */
 public boolean createFile(String templatePath, Map<String, Object> data,
                                          String outputPath) {
        try {
            // 获取Freemarker的Configuration
            Configuration cfg = getConfiguration();
            // 创建Template对象
            Template template = cfg.getTemplate(templatePath);
            // 生成静态页面
            Writer out = new BufferedWriter(new OutputStreamWriter(
                          new FileOutputStream(outputPath), "UTF-8"));
            template.process(data, out);
            out.flush();
            out.close();
        } catch (IOException | TemplateException e) {
            return false;
        }
        return true;
 }

在maven项目resources下创建templates文件夹,用于存放模版文件,然后新建一个test.ftl模版文件,即可根据这个文件来进行定制生成我们想要的静态文件。

测试

FreemarkerUtils f = new FreemarkerUtils ();
Map<String,Object> data = new HashMap<>();
data.put("name","hello world");
f.createFile("test.ftl",data,"D:\\test.ftl");

直接运行即可,就会看到D盘下生成我们需要的静态文件了。

相关文章

网友评论

      本文标题:利用Freemarker生成静态文件

      本文链接:https://www.haomeiwen.com/subject/dxzzqxtx.html