This is a working source file assembled from the previous
fragments. Don't forget to put freemarker.jar
into
the CLASSPATH
.
import freemarker.template.*; import java.util.*; import java.io.*; public class Test { public static void main(String[] args) throws Exception { /* ------------------------------------------------------------------------ */ /* You should do this ONLY ONCE in the whole application life-cycle: */ /* Create and adjust the configuration singleton */ Configuration cfg = new Configuration(Configuration.VERSION_2_3_29); cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates")); // Recommended settings for new projects: cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); cfg.setWrapUncheckedExceptions(true); cfg.setFallbackOnNullLoopVariable(false); /* ------------------------------------------------------------------------ */ /* You usually do these for MULTIPLE TIMES in the application life-cycle: */ /* Create a data-model */ Map root = new HashMap(); root.put("user", "Big Joe"); Product latest = new Product(); latest.setUrl("products/greenmouse.html"); latest.setName("green mouse"); root.put("latestProduct", latest); /* Get the template (uses cache internally) */ Template temp = cfg.getTemplate("test.ftlh"); /* Merge data-model with template */ Writer out = new OutputStreamWriter(System.out); temp.process(root, out); // Note: Depending on what `out` is, you may need to call `out.close()`. // This is usually the case for file output, but not for servlet output. } }
Note:
I have suppressed the exceptions for the sake of simplicity. Don't do it in real products.
For the sake completeness, here's the the Product class used in the data model:
/** * 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; } }
and the template:
Template
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${latestProduct.url}">${latestProduct.name}</a>! </body> </html>