创建一个数据模型
在简单的情况下,您可以使用java.lang
和java.util
类以及自定义 JavaBean 构建数据模型:
-
使用
java.lang.String
作为字符串。 -
对数字使用
java.lang.Number
子类。 -
将
java.lang.Boolean
用作布尔值。 -
使用
java.util.Date
及其子类作为日期/时间值 -
对序列使用
java.util.List
或 Java 数组。 -
将
java.util.Map
和String
键用于哈希。 -
将自定义 bean 类用于哈希项,其中项对应于 bean 属性。例如,
product
的price
属性(getPrice()
)可以作为product.price
获得。 (bean 的动作也可以公开;请稍后查看here)
例如,让我们构建模板作者指南的第一个示例的数据模型。为了方便起见,这里再次是:
(root)
|
+- user = "Big Joe"
|
+- latestProduct
|
+- url = "products/greenmouse.html"
|
+- name = "green mouse"
构建此数据模型的 Java 代码片段:
// Create the root hash. We use a Map here, but it could be a JavaBean too.
Map<String, Object> root = new HashMap<>();
// Put string "user" into the root
root.put("user", "Big Joe");
// Create the "latestProduct" hash. We use a JavaBean here, but it could be a Map too.
Product latest = new Product();
latest.setUrl("products/greenmouse.html");
latest.setName("green mouse");
// and put it into the root
root.put("latestProduct", latest);
如上所述,对于散列(存储其他命名项的散列),您可以使用Map
或具有 JavaBeans 规范规定的具有公共getXxx
/isXxx
方法的任何类型的公共类。像上面的Product
类可能是这样的:
/**
* Product bean; note that it must be a public class!
*/
public class Product {
private String url;
private String name;
// As per the JavaBeans spec., this defines the "url" bean property
// It must be public!
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
// As per the JavaBean spec., this defines the "name" bean property
// It must be public!
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
无论latestProduct
是包含"name"
和"url"
键的Map
,还是上面所示的 JavaBean,在模板中都可以使用${latestProduct.name}
。根本身也不必是Map
。它也可以是具有getUser()
和getLastestProduct()
方法的对象。
Note:
仅当object_wrapper
配置设置的值是几乎在所有实际设置中都使用过的值时,此处描述的行为才有效。 ObjectWrapper
包装为哈希的任何内容(实现TemplateHashModel
接口的内容)都可以用作根,并且可以在带有点和[]
运算符的模板中进行遍历。它不能包装成哈希的东西不能用作根或像这样遍历。