没有梦想,何必远方

使用Freemark生成静态HTML页面


  <!-- freemarker模版jar-相关依赖-->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>
package com.jy.common.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by jy on 2018/3/21.
 */

public class FreemarkerUtil {
    public static void main(String[] args) {
       createHtml();
    }
    public static void createHtml(String modelPath,String modelName,Map<String,Object> map){
        Configuration cfg = new Configuration();
        try {
            //cfg.setDirectoryForTemplateLoading(new File("C:/My/aaa/bbb"));  //设置读取模板文件的目录
            cfg.setDirectoryForTemplateLoading(new File(modelPath));  //设置读取模板文件的目录

           // Template t = cfg.getTemplate("index.ftl");  //读取文件名为Test.ftl的模板
            Template t = cfg.getTemplate(modelName);  //读取文件名为index.ftl的模板

            Map root = new HashMap();  //存储数据
            root.put("id",1);
            root.put("name","zhangsan");
            Writer out = new OutputStreamWriter(new FileOutputStream(
                    "C:/My/aaa/bbb/a.html"), "UTF-8");  //输出流

            t.process(root, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
            //t.process(map, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
        }catch(Exception e){

        }
        System.out.println("Create successfully!");
    }

}

 

posted @ 2018-03-29 23:32  北极丶光  阅读(231)  评论(0编辑  收藏  举报