创建数据模型
我们可以简单地使用java.lang java.util 和自定义的JavaBean构建对象模型,比如我们构建数据模型如下:
| | |
|
(root)
|
+- user = "Big Joe"
|
+- latestProduct
|
+- url = "products/greenmouse.html"
|
+- name = "green mouse" | | |
| | |
如下是构建数据模型的代码:
| | |
|
// Create the root hash
Map root = new HashMap();
// Put string ``user'' into the root
root.put("user", "Big Joe");
// Create the hash for ``latestProduct''
Map latest = new HashMap();
// and put it into the root
root.put("latestProduct", latest);
// put ``url'' and ``name'' into latest
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse"); | | |
| | |
也可以使用一个包含url 和 name 属性的JavaBean实例表示lastestProduct。
获取模板
模板通过freemarker.template.Template实例表示。通常从Configuration 实例中获取Template实例,任何时候都可以调用getTemplate方法获取一个Template 实例。假定模板文件test.ftl 保存在先前设置的目录中:
| | |
|
Template temp = cfg.getTemplate("test.ftl"); | | |
| | |
上述代码将读取,解析/where/you/store/templates/test.ftl文件,创建一个对应的Template实例 。
Configuration 缓存Template 实例, 因此当需要再次获取test.ftl 文件, 将不会创建一个新的Template实例。
合并模板和数据模型
就我们所知,数据模型+模板=输出,通过调用模板的process 方法合并数据模型和模板,process. 方法接受一个数据模型根和一个writer作为参数,将结果输出到Writer。 为简化起见,这里输出到控制台。
| | |
|
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush(); | | |
| | |
一旦获取一个Template 实例,可以合并不同的数据模型和一个模板(Template 实例基本上是无状态的),而test.ftl只会当Template 实例被创建的时候访问一次。
整合
这是先前代码片断的源文件,不要忘记将freemarker.jar放在CLASSPATH.中。
| | |
|
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
/* ------------------------------------------------------------------- */
/* You usually do it only once in the whole application life-cycle: */
/* Create and adjust the configuration */
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(
new File("/where/you/store/templates"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
/* ------------------------------------------------------------------- */
/* You usually do these for many times in the application life-cycle: */
/* Get or create a template */
Template temp = cfg.getTemplate("test.ftl");
/* Create a data model */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* Merge data model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
}
} | | |
| | |