通过上一篇freemarker的认识及实例(一)让我们对于Freemarker有了基本的一些了解,下面是我写的一些代码,参考一下。
package com.bw.bean;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class TestDemo {
public static void main(String[] args) throws IOException, TemplateException {
//创建Freemarker配置实例
Configuration cfg=new Configuration();
cfg.setDirectoryForTemplateLoading(new File("templates"));
//创建数据模型
Map<String,Object> map=new HashMap<String,Object>();
map.put("user", "hh");
//一个随机数
map.put("random", new Random().nextInt(100));
//一个list集合
List<Address> list=new ArrayList<Address>();
list.add(new Address("河北","衡水"));
list.add(new Address("河南","郑州"));
list.add(new Address("山东","德州"));
map.put("list", list);
map.put("date1", new Date());
//加载模板文件
Template template=cfg.getTemplate("a1.ftl");
//显示生成的数据
Writer out=new OutputStreamWriter(System.out);
template.process(map, out);
out.flush();
out.close();
}
}
a1.ftl的代码
<#list list as li>
${li.country}===${li.city}
</#list>
//获取到时间
${date1?string("yyyy-MM-dd HH:mm:ss")}
//用获取到的随机数进行if else 判断
<#if random gt 90>
"及格了"
<#else>
"不及格"
</#if>