FreeMarkerTest.java
package freemarker;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
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 javax.xml.crypto.Data;
import org.junit.Test;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkerTest {
@Test
public void testFreeMarker() throws IOException, TemplateException{
//创建一个模板文件
//创建一个Configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
//设置模板文件保存的目录
configuration.setDirectoryForTemplateLoading(new File("F:/GG/day0804 freemarker/demo工程/freemarker/WebContent/"));
//设置模板文件的编码格式
configuration.setDefaultEncoding("UTF-8");
//加载一个模板文件,创建一个模板对象
// Template template = configuration.getTemplate("hello.ftl");
Template template = configuration.getTemplate("student.ftl");
//创建一个数据集可以是pojo,也可以是map,推荐使用map
Map date=new HashMap<>();
date.put("hello", "hello freemarker");
//chuangjianygie 创建一个pojo对象
Student student = new Student(566666, "xiaoming", 18, "Uk");
date.put("student", student);
List<Student> list=new ArrayList<>();
list.add(new Student(342424, "绯fdsf", 18, "北京"));
list.add(new Student(674753, "xjhg", 18, "中南海"));
list.add(new Student(362464, "bnv3", 18, "五道湾"));
list.add(new Student(264562, "xihfgh4", 18, "二环城楼"));
list.add(new Student(243344, "jdgh", 18, "和平饭店"));
list.add(new Student(346878, "bytrn", 18, "东京"));
list.add(new Student(258890, "kumh", 18, "秋叶原"));
list.add(new Student(375645, "tyrhb", 18, "涩谷"));
date.put("list", list);
date.put("val",null);
//添加日期
date.put("date", new Date());
//创建一个Writer对象,执行输出文件的路径以及文件名。
Writer out=new FileWriter(new File("f:/GG/student.html"));
//生成静态页面
template.process(date, out);
//关闭流
out.close();
}
}
student.ftl
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>student</title>
</head>
<body>
学生信息:<br>
学号:${student.id}
姓名:${student.name}
年龄:${student.age}
地址:${student.address}<br>
<table border="1">
<tr>
<th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>家庭住址</th>
</tr>
<#list list as stu>
<#if stu_index % 2 == 0>
<tr bgcolor="#F4E8C3">
<#else>
<tr bgcolor="#6FFF3A">
</#if>
<th>${stu_index}</th>
<th>${stu.id}</th>
<th>${stu.name}</th>
<th>${stu.age}</th>
<th>${stu.address}</th>
</tr>
</#list>
</table>
${date?string("yyyy/MM/dd HH:mm:ss")}
null的值:${val!"cizhinull"}<br>
判断val的值是否为null<br>
<#if val??>
val有内容
<#else>
val为null
</#if>
引用模板测试<br>
<#include "hello.ftl">
</body>
</html>
hello.ftl
${hello}
<table border="1">
<#list list as stu>
<th>${stu_index}</th>
<th>${stu.id}</th>
<th>${stu.name}</th>
<th>${stu.age}</th>
<th>${stu.address}</th>
</tr>
</#list>
</table>