最近接触了一个freemark最为静态化页面的项目,特地从网上搜索,写了一个小案例。

freemark静态化页面主要有两部分组成:模板和数据

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

数据通过流传到模板中,之后使用freemark特有的指令,将数据取出。

现在开始freemark小案例吧。

1:创建一个普通的java工程

freemakr小案例 随笔 第1张

  三个红框分别代表的是2,3,4三个步骤

2:导入freemark.jar包

3:设置模板(注意模板的格式可以是任意,比如.html,.txt,.avi等等)


freemakr小案例 随笔 第2张

使用${}来获取数据


 4:编写测试类

package cn.zkr.freemark;


import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

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

public class FreeMarkDemo {

private static final String path="E:/zixue/freemarkDemo/template";
public static void main(String[] args) throws IOException, TemplateException {

// 1.设置配置类
Configuration configuration = new Configuration();
//2. 设置模板所在的目录
configuration.setDirectoryForTemplateLoading(new File(path));
//3.设置字符集
configuration.setDefaultEncoding("utf-8");
//3.设置字符集
configuration.setDefaultEncoding("utf-8");
//4.加载模板
Template template = configuration.getTemplate("NewFile.html");
//5.创建数据模型
HashMap<String,String> map= new HashMap();
map.put("name1","小红");
map.put("name2","小明");
//6.创建Writer对象
FileWriter writer = new FileWriter(new File("D:/test.html"));
//7.输出数据模型到文件中
template.process(map,writer);
//8.关闭Writer对象
writer.close();

}


}

5:测试结果

freemakr小案例 随笔 第3张

 

 

 

  

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄