一、基础知识点
1、同类型的产品还有Apache旗下Java开发的velocity;
2、Java语言编写的模板引擎,基于模板生成文本文件,比如生成Java、xml、jsp;
3、模板自己定义,数据也自己定义,但可以根据freemaker提供的方法使用自己定义的模板和数据生成想要的静态页面;
4、与web容器无关;
5、有数据和模板即可生成新的文件;
6、用于网页静态化,提高访问效率,适用于分布式系统;
二、使用步骤
1、项目pom文件中引入freemaker的jar包
2、编写如下测试代码
@Test
public void testFreemaker()throws Exception{
//创建一个freemaker的模板
//创建一个configuration对象,并设置当前freemaker的版本号
Configuration configuration = new Configuration(Configuration.getVersion());
//设置模板路径
configuration.setDirectoryForTemplateLoading(new File("D:\\dev_taotao\\taotao-item-web\\src\\main\\webapp\\WEB-INF\\ftl"));
//设置模板的编码格式为utf-8
configuration.setDefaultEncoding("utf-8");
//获取模板对象
// Template template = configuration.getTemplate("hello.ftl");
Template template = configuration.getTemplate("student.ftl");
//设置数据
Map data = new HashMap();
data.put("hello","hello freemaker");
Student student = new Student(1,"静静",26,"北京丰台区");
data.put("student",student);
List list = new ArrayList();
list.add( new Student(1,"静静1",26,"北京丰台区"));
list.add( new Student(2,"静静1",26,"北京丰台区"));
list.add( new Student(3,"静静2",26,"北京丰台区"));
list.add( new Student(4,"静静3",26,"北京丰台区"));
list.add( new Student(5,"静静4",26,"北京丰台区"));
data.put("studentList",list);
//新建输出流
Writer writer = new FileWriter("D:\\dev_taotao\\taotao-item-web\\src\\main\\webapp\\WEB-INF\\out\\student.html");
//写入模板
template.process(data,writer);
//关闭流
writer.close();
}
3、在对应ftl目录下新建模板文件student.ftl,内容如下,按照html语法和freemaker语法写即可:
本测试主要实现元素查看,对象内容输出和内容循环展现
<html>
<head>
<title>测试页面</title>
</head>
<body>
学生信息:<br>
学号:${student.id}<br>
姓名:${student.name}<br>
年龄:${student.age}<br>
家庭住址:${student.address}<br>
学生列表:<br>
<table border="1">
<tr>
<th>序号</th>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>家庭住址</th>
</tr>
<#list studentList as stu>
<#if stu_index%2==0>
<tr bgcolor="aqua">
<#else>
<tr bgcolor="#ff7f50">
</#if>
<td>${stu_index}</td>
<td>${stu.id}</td>
<td>${stu.name}</td>
<td>${stu.age}</td>
<td>${stu.address}</td>
</tr>
</#list>
</table>
</body>
</html>
4、执行测试代码
在浏览器输入文件输出路径,结果如下: