Freemarker's simplest example program
freemarker-2.3.18.tar.gz
http://cdnetworks-kr-1.dl.sourceforge.net/project/freemarker/freemarker/2.3.18/freemarker-2.3.18.tar.gz
freemarker-2.3.13.jar:
Link: http://pan.baidu.com/s/1eQVl9Zk Password: izs5
1. Create template objects through String and perform interpolation processing
After execution, the console outputs the result:
import freemarker.template.Template; import java.io.OutputStreamWriter; import java.io.StringReader; import java.util.HashMap; import java.util.Map; /** * The simplest example of Freemarker* * @author leizhimin 11-11-17 10:32 am */ public class Test2 { public static void main(String[] args) throws Exception{ //Create a template object Template t = new Template(null, new StringReader("Username: ${user};URL: ${url};Name: ${name}"), null); //Create interpolated Map Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "Baidu"); //Execute interpolation and output to the specified output stream t.process(map, new OutputStreamWriter(System.out)); } }Username: lavasoft;URL: http://www.baidu.com/;Name: Baidu Processfinishedwithexitcode0
2. Create template objects through files and perform interpolation operations
import freemarker.template.Configuration; import freemarker.template.Template; import java.io.File; import java.io.OutputStreamWriter; import java.util.HashMap; import java.util.Map; /** * The simplest example of Freemarker* * @author leizhimin 11-11-14 2:44 pm */ public class Test { private Configuration cfg; //template configuration object public void init() throws Exception { //Initialize FreeMarker configuration//Create a Configuration instance cfg = new Configuration(); //Set the template folder location of FreeMarker cfg.setDirectoryForTemplateLoading(new File("G://testprojects//freemarkertest//src")); } public void process() throws Exception { //Construct the Map Map map that fills the data Map map = new HashMap(); map.put("user", "lavasoft"); map.put("url", "http://www.baidu.com/"); map.put("name", "Baidu"); //Create the template object Template t = cfg.getTemplate("test.ftl"); //Perform interpolation operations on the template and output to the formulated output stream t.process(map, new OutputStreamWriter(System.out)); } public static void main(String[] args) throws Exception { Test hf = new Test(); hf.init(); hf.process(); } }Create template file test.ftl
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome ${user}!</h1> <p>Our latest product: <a href="${url}">${name}</a>! </body> </html> Hello, Dear user: Username: ${user}; URL: ${url}; Name: ${name}After execution, the console output results are as follows:
<html> <head> <title>Welcome!</title> </head> <body> <h1>Welcome lavasoft!</h1> <p>Our latest product: <a href="http://www.baidu.com/">Baidu</a>! </body> </html> Hello, Dear user: Username: lavasoft; URL: http://www.baidu.com/; Name: Baidu Process finished with exit code 0