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
1 name: ${name} 2 Age: ${age}
Java code
1 PackageCom.freemarker;2 3 ImportJava.io.File;4 Importjava.io.IOException;5 ImportJava.io.OutputStreamWriter;6 ImportJava.io.Writer;7 ImportJava.util.HashMap;8 ImportJava.util.Map;9 Ten Importfreemarker.template.Configuration; One Importfreemarker.template.Template; A Importfreemarker.template.TemplateException; - - Public classTest { the Public Static voidMain (string[] args)throwsIOException, templateexception { - - //1. Create a configuration instance cofiguration -Configuration cfg =NewConfiguration (); + - //2. Set the template file directory + //(1) directory under SRC directory (template under SRC) A //cfg.setdirectoryfortemplateloading (New File ("Src/template")); at //(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 (NewFile ("Template/main")); in //Cfg.setobjectwrapper (New Defaultobjectwrapper ()); - //get Templates (template) toTemplate template = Cfg.gettemplate ("TEST.FTL"); + //Building a data Model (MAP) -map<string, string> root =NewHashmap<string, string>(); theRoot.put ("name", "CXL"); *Root.put ("Age", "25"); $ //gets the output stream (specified to the console (standard output))Panax NotoginsengWriter out =NewOutputStreamWriter (System.out); - //StringWriter out = new StringWriter (); the //System.out.println (out.tostring ()); + //Data and template merging (data + template = output) A template.process (root, out); the Out.flush (); + } -}
Operation Result:
Java code
NAME:CXL 25
Examples of using Freemarker in Java Engineering