1. 程式人生 > >Freemarker簡單用法

Freemarker簡單用法

pri eem finished 初始 proc puts ade mar min

Freemarker 最簡單的例子程序 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 1、通過String來創建模版對象,並執行插值處理 import freemarker.template.Template;

import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.util.HashMap;
import
java.util.Map;

/**
* Freemarker最簡單的例子
*
* @author leizhimin 11-11-17 上午10:32
*/

public class Test2 {
public static void main(String[] args) throws Exception{
//創建一個模版對象
Template t = new Template(null, new StringReader("用戶名:${user};URL: ${url};姓名:  ${name}"), null
);
//創建插值的Map
Map map = new HashMap();
map.put("user", "lavasoft");
map.put("url", "http://www.baidu.com/");
map.put("name", "百度");
//執行插值,並輸出到指定的輸出流中
t.process(map, new OutputStreamWriter(System.out));
}
}
執行後,控制臺輸出結果: 用戶名:lavasoft;URL: http://www.baidu.com/;姓名:  百度
Process finished with exit code 0 2、通過文件來創建模版對象,並執行插值操作 import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

/**
* Freemarker最簡單的例子
*
* @author leizhimin 11-11-14 下午2:44
*/

public class Test {
private Configuration cfg; //模版配置對象

public void init() throws Exception {
//初始化FreeMarker配置
//創建一個Configuration實例
cfg = new Configuration();
//設置FreeMarker的模版文件夾位置
cfg.setDirectoryForTemplateLoading(new File("G:\\testprojects\\freemarkertest\\src"));
}

public void process() throws Exception {
//構造填充數據的Map
Map map = new HashMap();
map.put("user", "lavasoft");
map.put("url", "http://www.baidu.com/");
map.put("name", "百度");
//創建模版對象
Template t = cfg.getTemplate("test.ftl");
//在模版上執行插值操作,並輸出到制定的輸出流中
t.process(map, new OutputStreamWriter(System.out));
}

public static void main(String[] args) throws Exception {
Test hf = new Test();
hf.init();
hf.process();
}
}
創建模版文件test.ftl <html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome ${user}!</h1>
<p>Our latest product:
<a href="${url}">${name}</a>!
</body>
</html>

尊敬的用戶你好:
用戶名:${user};
URL: ${url};
姓名:  ${name} 執行後,控制臺輸出結果如下: <html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome lavasoft!</h1>
<p>Our latest product:
<a href="http://www.baidu.com/">百度</a>!
</body>
</html>

尊敬的用戶你好:
用戶名:lavasoft;
URL: http://www.baidu.com/;
姓名:  百度
Process finished with exit code 0

Freemarker簡單用法