访问freemarker中的嵌套映射时无效的引用异常

时间:2013-03-15 18:48:59

标签: freemarker

我有嵌套地图。

Map<String, Map<String, Long>> domains;

当我以下列方式访问它时,我得到InvalidReferenceException

<#list somelist as item>
  <#list domains[item]?keys as key>
    ${key}
  </#list>
</#list>

表达式域[item]未在线定义...

我尝试使用BeansWrapper和DefaultObjectWrapper。我也检查了地图上的内容,没有任何值为空。

1 个答案:

答案 0 :(得分:1)

同时适用于DefaultObjectWrapperBeansWrapper,因此我猜somelist包含一些错误的密钥。

这是我用过的测试代码;将模板放入test.ftl所在的目录所在的目录:

package adhoc;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;

public class TestTemplateRunner {

    public static void main(String[] args) throws FileNotFoundException, IOException, TemplateException {
        Configuration cfg = createConfiguration(false);

        cfg.getTemplate("test.ftl").process(
                createDataModel(),
                new OutputStreamWriter(System.out));
    }

    private static Configuration createConfiguration(boolean useBeansWrapper) {
        Configuration cfg = new Configuration();
        cfg.setClassForTemplateLoading(TestTemplateRunner.class, "");
        if (useBeansWrapper) {
            BeansWrapper bw = new BeansWrapper();
            bw.setSimpleMapWrapper(true);
            cfg.setObjectWrapper(bw);
        }
        return cfg;
    }

    private static Map<String, Object> createDataModel() {
        Map<String, Object> dataModel = new HashMap<String, Object>();

        Map<String, Map<String, Long>> domains = new HashMap<String, Map<String, Long>>();
        dataModel.put("domains", domains);

        Map<String, Long> domain1Hits = new HashMap<String, Long>();
        domain1Hits.put("/index", 1234L);
        domain1Hits.put("/about", 123L);
        domains.put("site1.com", domain1Hits);

        Map<String, Long> domain2Hits = new HashMap<String, Long>();
        domain2Hits.put("/", 2234L);
        domain2Hits.put("/contact", 223L);
        domains.put("site2.com", domain2Hits);

        List<String> somelist = new ArrayList<String>();
        somelist.add("site1.com");
        somelist.add("site2.com");
        dataModel.put("somelist", somelist);

        return dataModel;
    }

}