读书人

Freemarker基础知识(二)

发布时间: 2012-12-20 09:53:21 作者: rapoo

Freemarker基础知识(2)

废话不多说,接着上面来。

5. 程序开发

5.1?创建配置实例

Configuration cfg = new Configuration();cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));cfg.setObjectWrapper(new DefaultObjectWrapper());

?首先,应该创建一个freemarker.template.Configuration实例,然后调整它的设置。Configuration实例是存储 FreeMarker应用级设置的中央区域。同时,它也处理创建和缓存预解析模板的工作。

?

5.2 ?取得模板及输出

?

Template temp = cfg.getTemplate("XXXX.ftl");
?Writer out = new OutputStreamWriter(System.out);temp.process(root, out);//root是程序处理完的一个Map对象。out.flush();

?? ?看来还是有必要把完整代码放出来啊。

import freemarker.template.*;import java.util.*;import java.io.*;public class Test {public static void main(String[] args) throws Exception {Configuration cfg = new Configuration();cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));cfg.setObjectWrapper(new DefaultObjectWrapper());Template temp = cfg.getTemplate("test.ftl");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");Writer out = new OutputStreamWriter(System.out);temp.process(root, out);out.flush();}}
??

读书人网 >编程

热点推荐