New Java project, introducing Freemarker.jar, the version of this project: freemarker-2.3.20 version
The Java Engineering catalog is as follows:
TEST.FTL file
HTML code
- Name: ${name}
- Age: ${age}
Test class
Java code
- Package com.freemarker;
- Import Java.io.File;
- Import java.io.IOException;
- Import Java.io.OutputStreamWriter;
- Import Java.io.Writer;
- Import Java.util.HashMap;
- Import Java.util.Map;
- Import freemarker.template.Configuration;
- Import Freemarker.template.Template;
- Import freemarker.template.TemplateException;
- Public class Test {
- public static void Main (string[] args) throws IOException, templateexception {
- //1. Creating a configuration instance cofiguration
- Configuration cfg = new configuration ();
- //2. Setting the template file directory
- //(1) directory under SRC directory (template under SRC)
- //cfg.setdirectoryfortemplateloading (New File ("Src/template"));
- //(2) Full path (template under SRC)
- //cfg.setdirectoryfortemplateloading (New File (
- //"d:/cpic-env/workspace/javafreemarker/src/template"));
- //cfg.setdirectoryfortemplateloading (New File ("Src/template"));
- //(3) catalogue under the Engineering catalogue (Template/main under Engineering)--recommended
- Cfg.setdirectoryfortemplateloading (new File ("Template/main"));
- //cfg.setobjectwrapper (New Defaultobjectwrapper ());
- //Get Templates (template)
- Template template = Cfg.gettemplate ("TEST.FTL");
- //Build Data Model (MAP)
- map<string, string> root = new hashmap<string, string> ();
- Root.put ("name", "CXL");
- Root.put ("age", "25");
- //Get output stream (specified to console (standard output))
- Writer out = new OutputStreamWriter (System.out);
- //stringwriter out = new StringWriter ();
- //system.out.println (out.tostring ());
- //Data and template merging (data + template = output)
- Template.process (root, out);
- Out.flush ();
- }
- }
Operation Result:
Java code
- Name:cxl
- Age:
Examples of using Freemarker in Java Engineering