一个简单的运用freemark的入门程序:
1.引入freemarker的jar包。
2.创建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}
3.创建java项目,新建Test.class类:
package com.zjy.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;
public class Test {
//C:\Users\Administrator\Desktop
private Configuration config; //配置模板对象
public void init() throws Exception{
//初始化FreeMarker配置
//创建一个Configuration实例
config = new Configuration();
//设置FreeMarker模板文件夹位置
config.setDirectoryForTemplateLoading(new File("C:\\Users\\Administrator\\Desktop"));
}
public void process() throws Exception{
//构造填充数据的Map
Map map = new HashMap();
map.put("user", "tom");
map.put("url", "www.baidu.com");
map.put("name", "百度");
//创建模板对象
Template t = config.getTemplate("test.html");
t.process(map, new OutputStreamWriter(System.out));
}
public static void main(String[] args) throws Exception {
Test t = new Test();
t.init();
t.process();
}
}
运行结果为:
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<h1>Welcome tom!</h1>
<p>Our latest product:
<a href="www.baidu.com">百度</a>!
</body>
</html>
尊敬的用户你好:
用户名: tom;
URL: www.baidu.com;
姓名: 百度