FreeMaker概念: 数据模型+模板=输出
创建Configuration实例
首先你必须创建一个freemarker.template.Configuration
实例,一个Configuration
实例是储存Freemaker应用程序级别的设置,此外还涉及到创建和缓存预解析模板( Template
对象 )
通常,你只会在程序开始时创建一个实例
警告: 没有必要反复的创建Configuration实例,由于失去了模板缓存,因此开销很大,Configuration实例应该是应用程序级别的单例
创建数据模型
在简单的情况下,您可以使用java.lang和java.util类和自定义JavaBean
// Create the root hash. We use a Map here, but it could be a JavaBean too.
Map<String, Object> root = new HashMap<>();
// Put string "user" into the root
root.put("user", "Big Joe");
// Create the "latestProduct" hash. We use a JavaBean here, but it could be a Map too.
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
// and put it into the root
root.put("latestProduct", latest);
上面使用Map来构建数据模型。
当然你也可以用JavaBean封装
/**
* Product bean; note that it must be a public class!
*/
public class Product {
private String url;
private String name;
// As per the JavaBeans spec., this defines the "url" bean property
// It must be public!
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
// As per the JavaBean spec., this defines the "name" bean property
// It must be public!
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
不管你是用Map的方式,还是JavaBean的方式,都可以在模板中使用${latestProduct.name}
或者其他语法
获取模板
模板是通过freemarker.template.Template
实例体现的,通常,你将会从Configuration
实例中获取Template
实例
例子:
Template temp = cfg.getTemplate("XXX.ftlh");
这个Template
实例是通过解析储存模板,而不仅仅是文本文档( TxT ),如果这个模板不存在,getTemplate
方法将会抛出异常
Configuration
实例会缓存Template
实例,所以当你调用Template temp = cfg.getTemplate("XXX.ftlh");
的下一次,它可能不会再次读取和解析文件了,只是会返回第一次的结果
将模板与数据模型合并
正如您可能已经知道的,数据模型+模板=输出。我们已经有了一个数据模型(root)和模板(temp),因此,为了获得输出,我们必须合并它们。这是由process模板的方法。它以数据模型根和Writer作为参数。它将产生的输出写入Writer。为了简单起见,我写到标准输出:
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
有关于Java I/O的:您必须确保使用out.close()
关闭流