创建一个数据模型

在简单的情况下,您可以使用java.langjava.util类以及自定义 JavaBean 构建数据模型:

例如,让我们构建模板作者指南的第一个示例的数据模型。为了方便起见,这里再次是:

(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接口的内容)都可以用作根,并且可以在带有点和[]运算符的模板中进行遍历。它不能包装成哈希的东西不能用作根或像这样遍历。

上一章 首页 下一章