FreeMarker的使用比较简单,只需要一个FreeMarker的jar包即可。
FreeMarker项目地址
http://freemarker.org/,中文手册地址:
http://sourceforge.net/projects/freemarker/files/chinese-manual/
1.新建一个java project,命名为:FreemarkerTest。
2.导入jar包:
freemarker.jar
junit-4.10.jar
3.新建一个文件夹,命名templates,在该目录下新建两个模板,01.ftl和02.ftl:
01.ftl:
4.编写一个FreeMarker的工具类:
你好:${username}
02.ftl:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${username}</h1>
</body>
</html>
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkerUtil {
// 负责管理FreeMarker模板的Configuration实例
private Configuration cfg = null;
/**
* 获取freemarker模板
* @param filename 文件名
* @return 返回freemarker模板
*/
public Template getTemplate(String filename) {
try {
cfg = new Configuration();
// 指定FreeMarker模板文件的位置
String filepath = System.getProperty("user.dir");
cfg.setDirectoryForTemplateLoading(new File(filepath+"/templates"));
//获取模板文件
Template template = cfg.getTemplate(filename);
return template;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 输出到控制台
* @param filename 模板文件名
* @param root 数据模型
*/
public void print(String filename,Map root) {
try {
Template template = getTemplate(filename);
template.process(root, new PrintWriter(System.out));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 输出到文件
* @param filename 模板文件名
* @param root 数据模型
* @param outFilename 输出的文件名
*/
public void printf(String filename,Map<String,String> root,String outFilename) {
try {
Template template = getTemplate(filename);
FileWriter fw = new FileWriter(new File("d:/" + outFilename));
template.process(root, fw);
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.新建一个测试类:
public class FreemarkerTest {
FreemarkerUtil fu = null;
Map<String,String> root = null;
@Before
public void init() {
fu = new FreemarkerUtil();
root = getHashMapInstance();
}
@Test
public void testPrint() {
root.put("username", "abc");
fu.print("01.ftl", root);
fu.print("02.ftl", root);
}
@Test
public void getPath() {
File f = new File(this.getClass().getResource("/").getPath());
System.out.println(f);
System.out.println(System.getProperty("user.dir"));
}
public <K,V>Map getHashMapInstance() {
return new HashMap<K,V>();
}
}
总结:
1.用了2个模板只是为了说明FreeMarker无论什么格式的文件都能处理,其实就是把${}部分替换成Map里相同key的value。
代码地址: