一、 概述
freemarker是java编写的一款模版引擎,是一种基于模版和要改变的数据,并用于输出文本(html、电子邮件、配置文件和源代码等)的通用工具。与web容器无关,即在web运行时,它并不知道servlet或HTTP。不仅可以用于表现层的实现技术,还可以用于生成XML,JPS或java等。在企业中,一般用于生成静态页面或是页面展示。
二、 使用freemarker
导入jar包或者引入依赖。
编写测试程序。
创建一个最简单的模版
在webapp的WEB-INF目录下,新建ftl目录,新建hello.ftl,一般是ftl后缀,也可以使用其他的。
${hello}
测试程序
@Test
publicvoid testFreemarker() throws Exception {
// 创建模版文件
// 创建Configuration对象
Configuration configuration = newConfiguration(Configuration.getVersion());
// 设置模版文件的保存路径
configuration.setDirectoryForTemplateLoading(
new File("H:\\001java\\eclipseSTSworkspace\\e3-item-web\\src\\main\\webapp\\WEB-INF\\ftl"));
// 设置默认文件的编码格式,一般是utf-8
configuration.setDefaultEncoding("utf-8");
// 加载一个模版文件,创建一个模版对象
Template template = configuration.getTemplate("hello.ftl");
// 创建一个数据集,pojo或者map
Map map = newHashMap<>();
map.put("hello", "你好福瑞马克");
// 创建一个Writer对象,指定输出文件的路径名及文件名
Writer out = new FileWriter(new File("H:\\vv\\hello.txt"));
// 生成静态页面
template.process(map, out);
// 关闭流
out.close();
}
三、 freemarker语法
1. 访问pojo属性
创建一个student的pojo。
创建模版
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8" />
<title>学生</title>
</head>
<body>
学生信息<br />
<table>
<tr>
<td>id</td>
<td>姓名</td>
<td>年龄</td>
<td>地址</td>
</tr>
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.age}</td>
<td>${student.address}</td>
</tr>
</table>
</body>
</html>
编写根据模版创建html文件的方法。
@Test
public void testFreemarker2()throws Exception {
// 创建模版文件
// 创建Configuration对象
Configuration c