freemarker使用步骤(转)

来源:互联网 发布:java vo bo po 编辑:程序博客网 时间:2024/05/17 01:14

                                                       freemarker使用步骤

1.创建配置实例

首先,必须创建一个freemarker.template.Configuration实例,并调整其设置。 A Configuration instance is a central place to store the application level settings of FreeMarker. 配置实例是一个中心位置来存储应用程序级别设置FreeMarker 。 Also, it deals with the creation and caching of pre-parsed templates.此外,它涉及建立和缓存预解析模板。 Probably you will do it only once at the beginning of the application (possibly servlet) life-cycle:也许你会做到这一点只有一次开始的时候,应用程序(可能的servlet )生命周期:

Configuration cfg = new Configuration();// Specify the data source where the template files come from.// Here I set a file directory for it:cfg.setDirectoryForTemplateLoading(new File("模板路径"));//cfg.setServletContextForTemplateLoading(this.getServletContext(), "模板路径");

//cfg.setClassForTemplateLoading(this.class,” 模板路径”)

// Specify how templates will see the data-model. This is an advanced topic...// but just use this:cfg.setObjectWrapper(new DefaultObjectWrapper()); 2创建数据模型在简单的情况下,您可以建立数据模型使用java.lang和java.util定制的Java类和Bean:

·         Use java.lang.String for strings.使用构造函数的字符串。

·         Use java.lang.Number descents for numbers.使用java.lang.Number的数字。

·         Use java.lang.Boolean for boolean values.使用java.lang.Boolean的Boolean值。

·         Use java.util.List or Java arrays for sequences.使用java.util.List或Java的arrays。

·         Use java.util.Map for hashes.使用java.util.Map的哈希。

·         Use your custom bean class for hashes where the items correspond to the bean properties.使用您自定义的bean类哈希的项目相对应的bean属性。 For example the price property of product can be get as product.price .例如知识产权的产品的价格可以得到作为product.price 。 (The actions of the beans can be exposed as well; see much later here )

(root)  |  +- user = "Big Joe"  |  +- latestProduct      |      +- url = "products/greenmouse.html"      |      +- name = "green mouse"    // Create the root hashMap root = new HashMap();// Put string ``user'' into the rootroot.put("user", "Big Joe");// Create the hash for ``latestProduct''Map latest = new HashMap();// put ``url'' and ``name'' into latest latest.put("url", "products/greenmouse.html");latest.put("name", "green mouse"); // and put it into the root root.put("latestProduct", latest);3获取模板模板是由freemarker.template.Template情况。 Typically you obtain a Template instance from the Configuration instance.通常你获得模板实例从Configuration实例。 Whenever you need a template instance you can get it with its getTemplate method.当你需要一个模板例如你可以用它getTemplate方法。 Store the example template in the test.ftl file of the earlier set directory, then you can do this: test.ftl文件早先设定的目录,那么你可以Template temp = cfg.getTemplate("test.ftl");

When you call this, it will create a Template instance corresponds to test.ftl , by reading /where/you/store/templates/ test.ftl and parsing (compile) it.它会创建一个Template实例对应于test.ftl ,通过阅读 模板路径/test.ftl和解析它。 The Template instance stores the template in the parsed form, and not as text.Template实例存储的模板中的解析形式,而不是文字。 Configuration caches Template instances, so when you get test.ftl again, it probably will not create new Template instance (thus doesn't read and parse the file), just returns the same instance as for the first time.Configuration缓存Template实例,因此当你再次解析test.ftl,它可能不会创建新的Template实例,只需返回同一例如,第一次。

4. 合并模板与数据模型

数据模型+模板=输出,我们有一个数据模型和模板 ,所以获得的产出,我们必须将它们合并。 This is done by the process method of the template.

Writer out = new OutputStreamWriter(System.out);temp.process(root, out);out.flush();  //PrintWriter p = new PrintWriter(new FileOutputStream(new File("1.html")));//如果为servelet则    response.getOutputStream()

// temp.process(root, p); This will print to your terminal the output what you have seen in the first example of the Template Author's Guide. Once you have obtained a Template instance, you can merge it with different data-models for unlimited times ( Template instances are basically stateless).

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

全部代码:

  //创建配置实例
  Configuration cfg = new Configuration();
  try {
   cfg.setDirectoryForTemplateLoading(new File("D:/apache-tomcat-6.0.18/webapps/email/"));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  cfg.setObjectWrapper(new DefaultObjectWrapper());
  //创建数据模型
  Map root = new HashMap();
  root.put("body", "body");
  Map latest = new HashMap();
  latest.put("url", "email/body.html");
  latest.put("name", "green mouse"); // and put it into the root
  root.put("email", latest);
  
  //获取模板
  try {
   Template temp = cfg.getTemplate("body.html");
   //把模板和数据模型合并输出
   Writer out = new OutputStreamWriter(System.out);       
   temp.process(root, out);      
   out.flush();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/luobintianya/archive/2009/02/17/3899971.aspx

原创粉丝点击