关于freeMarker的介绍,在这里就不具体的说明了,请大家自行Google,我们把时间放到代码上。
最近因为公司的要求,我从iOS方向转到了JAVA后台,今天刚刚接触了用java语言编写的模板引擎。我们从最简单的开始,Demo如下:
开始工程的准备jar包的地址。
在eclipse中创建Freemarker模板
你好 ${user} ${userPassword} 今天的精神不错
- 创建FreemarkerUtil类。类中的全部代码如下:
package a.text.client;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class FreeMarkertUtil {
public static void main(String [] args) throws Exception {
// 创建Configuration上下文,并设置路径
Configuration config = new Configuration();
config.setDirectoryForTemplateLoading(new File("templace"));//templace为工程目录下的一个文件夹
//创建数据模型
Map root = new HashMap();
root.put("user", "科比");
root.put("userPassword", "878667");
//加载模型文件
Template template = config.getTemplate("a.ftl");//a.ftl是templace工程目录下所建立的ftl文件
//显示所生成的数据
Writer out = new OutputStreamWriter(System.out);
template.process(root, out);
out.flush();
out.close();
}
}
运行之后,在控制台打印的是:
你好 科比 878667 今天的精神不错