package com.ninemax.test;
import java.io.File;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* 通过文件来创建模版对象,并执行插值操作
*
* @author Darker
*
*/
public class FreeMarkerByFile {
// 模板配置对象
private Configuration cfg;
@SuppressWarnings("all")
public void inin() throws Exception {
// 初始化FreeMarker配置
// 创建一个Configuration实例
cfg = new Configuration();
// 设置FreeMarker的模板文件夹位置
cfg.setDirectoryForTemplateLoading(new File("D:\\freemarker\\src"));
}
public void process() throws Exception {
// 构造填充数的Map
Map<String, String> map = new HashMap<String, String>();
map.put("user", "Darker");
map.put("name", "百度");
map.put("url", "http://www.baidu.com");
// 创建模板对象
Template t = cfg.getTemplate("freemarker.ftl");
// 在模板上执行插值操作,并输出到指定的输出流中
t.process(map, new OutputStreamWriter(System.out));
}
public static void main(String[] args) throws Exception {
FreeMarkerByFile fm = new FreeMarkerByFile();
fm.inin();
fm.process();
}
}
文件内容(freemarker.ftl):
<html>
<head>
<title>FreeMarker</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>FreeMarker</title>
</head>
<body>
<h1>WelcomeDarker!</h1>
<p>Our latest product:
<a href="http://www.baidu.com">百度</a>
</body>
</html>
尊敬的用户你好:
用户名:Darker;
URL: http://www.baidu.com;
姓名: 百度