1、模板文件
这里使用到了简单的取值、判断null并设置默认值、循环遍历list、日期格式、if else判断、include
<html>
<head>
<title>${title!"DefaultTitle"}</title>
</head>
<body>
<p>网页描述:${desc!"是一个测试"}</p>
<lable>second的内容:</lable><br>
<#include "second.ftl"><br><br>
<table border="1">
<tr>
<td>下标</td>
<td>学号</td>
<td>姓名</td>
<td>住址</td>
</tr>
<#list stus as s>
<#if s_index % 3 == 0>
<tr style="color:blue">
<#elseif s_index % 3 == 1>
<tr style="color:yellow">
<#elseif s_index % 3 == 2>
<tr style="color:red">
</#if>
<td>${s_index}</td>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.addr}</td>
</tr>
</#list>
</table><br>
<lable>日期格式</lable>
<#if currDate??>
<lable>data:</lable>${currDate?date}<br>
<lable>time:</lable>${currDate?time}<br>
<lable>datatime:</lable>${currDate?datetime}<br>
<lable>自定义:</lable>${currDate?string("yyyy年MM月dd日 HH:mm:ss")}<br>
<#else>
<lable>data为空</lable>
</#if>
</body>
</html>
2、Java测试代码
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 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 {
// 1、添加jar包到工程中國
// 2、freemarker不依賴于web容器
// 3、创建Configuration对象
Configuration configuration = new Configuration(Configuration.getVersion());
// 4、设置模板存放位置
configuration.setDirectoryForTemplateLoading(new File("D:\\WorkSpace\\FairyShop\\fairyshop-portal\\src\\main\\webapp\\WEB-INF\\ftl"));
// 5、设置默认字符集
configuration.setDefaultEncoding("utf-8");
// 6、获得指定的模板对象
Template template = configuration.getTemplate("third.ftl");
// 7、创建模板需要的数据集,可以是map,也可以是pojo
Map root = new HashMap<>();
root.put("title", "world");
root.put("stu", new Student(2, "Bob", "西安"));
List<Student> stus = new ArrayList<>();
stus.add(new Student(1, "Mary01", "China01"));
stus.add(new Student(2, "Mary02", "China02"));
stus.add(new Student(3, "Mary03", "China03"));
stus.add(new Student(4, "Mary04", "China04"));
stus.add(new Student(5, "Mary05", "China05"));
stus.add(new Student(6, "Mary06", "China06"));
root.put("stus", stus);
root.put("currDate", new Date());
// 8、创建Writer对象,指定html输出路径
Writer out = new FileWriter(new File("E:\\Temp\\html\\third.html"));
// 9、调用模板对象的process方法,生成静态页面
template.process(root, out);
// 10、关闭writer对象
out.flush();
out.close();
}
public class Student{
private int id;
private String name;
private String addr;
public Student(int id, String name, String addr) {
this.id = id;
this.name = name;
this.addr = addr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
}
}