学习笔记,选自freeMarker中文文档,译自 Email: ddekany at users.sourceforge.net

1.创建Configuration实例

  首先,你应该创建一个 freemarker.template.Configuration 实例, 然后调整它的设置。Configuration 实例是存储 FreeMarker 应用级设置的核心部分。同时,它也处理创建和 缓存 预解析模板(比如 Template 对象)的工作。

  也许你只在应用(可能是servlet)生命周期的开始执行一次

 // Create your Configuration instance, and specify if up to what FreeMarker
 // version (here 2.3.22) do you want to apply the fixes that are not 100%
 // backward-compatible. See the Configuration JavaDoc for details.
 Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);

 // Specify the source where the template files come from. Here I set a
 // plain directory for it, but non-file-system sources are possible too:
 cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));

 // Set the preferred charset template files are stored in. UTF-8 is
 // a good choice in most applications:
 cfg.setDefaultEncoding("UTF-8");

 // Sets how errors will appear.
 // During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.
 cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

  从现在开始,应该使用单实例配置(也就是说,它是单例的)。 请注意不管一个系统有多少独立的组件来使用 FreeMarker, 它们都会使用他们自己私有的 Configuration 实例。

警告:不需要重复创建 Configuration 实例; 它的代价很高,尤其是会丢失缓存。Configuration 实例就是应用级别的单例。

  当使用多线程应用程序(比如Web网站),Configuration 实例中的设置就不能被修改。它们可以被视作为 "有效的不可改变的" 对象, 也可以继续使用 安全发布 技术 (参考 JSR 133 和相关的文献)来保证实例对其它线程也可用。比如, 通过final或volatile字段来声明实例,或者通过线程安全的IoC容器,但不能作为普通字段。 (Configuration 中不处理修改设置的方法是线程安全的。)

2.创建数据模型

  在简单的示例中你可以使用 java.langjava.util 包中的类, 还有用户自定义的Java Bean来构建数据对象:

  • 使用 java.lang.String 来构建字符串。

  • 使用 java.lang.Number 来派生数字类型。

  • 使用 java.lang.Boolean 来构建布尔值。

  • 使用 java.util.List 或Java数组来构建序列。

  • 使用 java.util.Map 来构建哈希表。

  • 使用自定义的bean类来构建哈希表,bean中的项和bean的属性对应。比如, productprice 属性 (getProperty())可以通过 product.price 获取。(bean的action也可以通过这种方式拿到; 要了解更多可以参看 这里)

  我们为 模板开发指南部分演示的第一个例子 来构建数据模型。为了方便说明,这里再展示一次示例:

(root)
  |
  +- user = "Big Joe"
  |
  +- latestProduct
      |
      +- url = "products/greenmouse.html"
      |
      +- name = "green mouse"

  下面是构建这个数据模型的Java代码片段:

 // Create the root hash
 Map<String, Object> root = new HashMap<>();
 // Put string ``user'' into the root
 root.put("user", "Big Joe");
 // Create the hash for ``latestProduct''
 Map<String, Object> 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");

  在真实应用系统中,通常会使用应用程序指定的类来代替 Map, 它会有JavaBean规范规定的 getXxx/isXxx 方法。比如有一个和下面类似的类:

 public class Product {

     private String url;
     private String name;
     ...

     // As per the JavaBeans spec., this defines the "url" bean property
     public String getUrl() {
         return url;
     }

     // As per the JavaBean spec., this defines the "name" bean property
     public String getName() {
         return name;
     }

     ...

 }

  将它的实例放入数据模型中,就像下面这样:

 Product latestProducts = getLatestProductFromDatabaseOrSomething();
 root.put("latestProduct", latestProduct);

  如果latestProductMap类型, 模板就可以是相同的,比如 ${latestProduct.name} 在两种情况下都好用。

  根root本身也无需是 Map,只要是有 getUser()getLastestProduct() 方法的对象即可。

注意:如果配置设置项 object_wrapper 的值是用于所有真实步骤, 这里描述的行为才好用。任何由 ObjectWrapper 包装成的哈希表 可以用作根root,也可以在模板中和点、 [] 操作符使用。 如果不是包装成哈希表的对象不能作为根root,也不能像那样在模板中使用。

3.获取模板

  模板代表了 freemarker.template.Template 实例。典型的做法是从 Configuration 实例中获取一个 Template 实例。无论什么时候你需要一个模板实例, 都可以使用它的 getTemplate 方法来获取。在 之前 设置的目录中的 test.ftl 文件中存储 示例模板,那么就可以这样来做:

Template temp = cfg.getTemplate("test.ftl");

  当调用这个方法的时候,将会创建一个 test.ftlTemplate 实例,通过读取 /where/you/store/templates/test.ftl 文件,之后解析(编译)它。Template 实例以解析后的形式存储模板, 而不是以源文件的文本形式。

  Configuration 缓存 Template 实例,当再次获得 test.ftl 的时候,它可能再读取和解析模板文件了, 而只是返回第一次的 Template 实例。

4.合并模板和数据模型

  我们已经知道,数据模型+模板=输出,我们有了一个数据模型 (root) 和一个模板 (temp), 为了得到输出就需要合并它们。这是由模板的 process 方法完成的。它用数据模型root和 Writer 对象作为参数,然后向 Writer 对象写入产生的内容。 为简单起见,这里我们只做标准的输出:

 Writer out = new OutputStreamWriter(System.out);
 temp.process(root, out);

  这会向你的终端输出你在模板开发指南部分的 第一个示例 中看到的内容。

  Java I/O 相关注意事项:基于 out 对象,必须保证 out.close() 最后被调用。当 out 对象被打开并将模板的输出写入文件时,这是很电影的做法。其它时候, 比如典型的Web应用程序,那就 不能 关闭 out 对象。FreeMarker 会在模板执行成功后 (也可以在 Configuration 中禁用) 调用 out.flush(),所以不必为此担心。

  请注意,一旦获得了 Template 实例, 就能将它和不同的数据模型进行不限次数 (Template实例是无状态的)的合并。此外, 当 Template 实例创建之后 test.ftl 文件才能访问,而不是在调用处理方法时。

5.将代码放在一起

  这是一个由之前的代码片段组合在一起的源程序文件。 千万不要忘了将 freemarker.jar 放到 CLASSPATH 中。

 import freemarker.template.*;
 import java.util.*;
 import java.io.*;

 public class Test {

     public static void main(String[] args) throws Exception {

         /* ------------------------------------------------------------------------ */
         /* You should do this ONLY ONCE in the whole application life-cycle:        */    

         /* Create and adjust the configuration singleton */
         Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
         cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
         cfg.setDefaultEncoding("UTF-8");
         cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW);

         /* ------------------------------------------------------------------------ */
         /* You usually do these for MULTIPLE TIMES in the application life-cycle:   */    

         /* 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");

         /* Get the template (uses cache internally) */
         Template temp = cfg.getTemplate("test.ftl");

         /* Merge data-model with template */
         Writer out = new OutputStreamWriter(System.out);
         temp.process(root, out);
         // Note: Depending on what `out` is, you may need to call `out.close()`.
         // This is usually the case for file output, but not for servlet output.
     }
 }
注意:为了简单起见,这里压制了异常(在方法签名中声明了异常), 而在正式运行的产品中不要这样做。
 
译自 Email: ddekany at users.sourceforge.net

最新文章

  1. javaweb常见问题解决
  2. MS Project 使用之创建项目信息
  3. ECMAScript —— 学习笔记(思维导图版)
  4. Yii源码阅读笔记(一)
  5. ARM寻址方式
  6. Mybatis 学习-2
  7. 解决COS、FileUpload上传文件时中文文件名乱码问题
  8. jQuery过滤选择器:not()方法使用介绍
  9. bzoj2730 [HNOI2012]矿场搭建 (UVAlive5135 Mining Your Own Business)
  10. HDOJ--ACMSteps--2.1.8--Leftmost Digit-(取对数,数学)
  11. XSS攻击过滤处理
  12. Linux基本操作——文件相关
  13. day 7-22 进程,线程,协程
  14. Javaweb学习笔记——(十一)——————JSP、会话跟踪、Cookie、HttpSession
  15. python-多线程等概念
  16. L258 技术转让
  17. vim 自动注释
  18. Cecos国内集成系统基于rhel6.5
  19. phonegap android插件,启动activity并返回值
  20. 设置nginx反向代理将80端口转发到9999端口

热门文章

  1. 卸载系统自带libevent
  2. pycharm的安装和破解
  3. python高级-------python2.7教程学习【廖雪峰版】(四)
  4. mysql慢查询日志分析工具(python写的)
  5. 【BZOJ1444】[Jsoi2009]有趣的游戏 AC自动机+概率DP+矩阵乘法
  6. Eight(经典题,八数码)
  7. 打包合并多个dll
  8. jQuery.callbacks 注释
  9. Spring 拦截器——HandlerInterceptor
  10. Qt Creator 调试器 在 Ubuntu 13.10下 局部变量和表达式(Locals) 无内容