Sto studiando utilizzando FreeMarker per scrivere file EDI. Si tratta di fatture elettroniche sostanzialmente formattate (e convalidate). Ho deciso di iniziare scrivendo un semplice esempio e sono bloccato a farlo diventare un "pojo annidato". Con questo intendo un POJO che contiene POJO in cui entrambi hanno dati che voglio nel mio output. Ho scritto un test unitario (autonomo) che sta fallendo per un motivo sconosciuto. Quando eseguo il test ottengo la seguente eccezione:Come utilizzare FreeMarker nel modello Pojos annidato?
Expression user.getSub is undefined on line 1, column 24 in simple.
The problematic instruction:
----------
==> ${user.getSub().user} [on line 1, column 22 in simple]
----------
Java backtrace for programmers:
----------
freemarker.core.InvalidReferenceException: Expression user.getSub is undefined on line 1, column 24 in simple.
at freemarker.core.TemplateObject.assertNonNull(TemplateObject.java:124)
at freemarker.core.TemplateObject.invalidTypeException(TemplateObject.java:134)
<snip>
example.TestFreeMarkerTemplating.testSimpleTemplate(TestFreeMarkerTemplating.java:23)
<snip>
Ho provato molte varianti sul modello e non ho raggiunto il successo. Questo è il test:
package example;
import java.io.*;
import org.junit.Test;
import freemarker.cache.StringTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.*;
import static org.junit.Assert.*;
public class TestFreeMarkerTemplating {
Configuration cfg = new Configuration();
StringTemplateLoader stringLoader = new StringTemplateLoader();
{ cfg.setTemplateLoader(stringLoader);
cfg.setObjectWrapper(new BeansWrapper()); }
@Test
public void testSimpleTemplate() throws TemplateException, IOException{
stringLoader.putTemplate("simple", "Welcome ${user}. Sub ${user.getSub().user}");
Template temp = cfg.getTemplate("simple");
StringWriter out = new StringWriter();
temp.process(new TestPojo(), out);
assertEquals("Welcome Andy. Sub Bill", out.toString());
}
public static class TestPojo {
private final String user = "Andy";
private final SubPojo sub = new SubPojo();
public String getUser() { return user; }
public SubPojo getSub() { return sub; }
}
public static class SubPojo {
private final String user = "Bill";
public String getUser() { return user; }
}
}
Grazie per qualsiasi aiuto!
Grazie. Lo fissavo da così tanto tempo che mi ero convinto che FreeMarker si sbagliava. La tua risposta è chiara e molto apprezzata. – Spina