创建数据模型

在简单的示例中你可以使用 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() 方法的对象即可。

Note:

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