1.加入对应的包——>fremarker.jar
2.开发一个模板
src/ templates下创建demo.ftl文件
写入
<!DOCTYPE HTML PUBLIC "-//W<?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /><chmetcnv w:st="on" tcsc="0" numbertype="1" negative="False" hasspace="False" sourcevalue="3" unitname="C">3C</chmetcnv>//DTD HTML 4.01 Transitional//EN"<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>
<body align="center">
${userName},欢迎你!
<#list list as name>
${name}<br/>
</#list>
</body>
</html>
3.开发一个测试类:
Test.java
package test;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class test {
public static void main(String[] args) {
try {
Configuration config=new Configuration();
File file=new File("src/templates");
//设置要解析的模板所在的目录,并加载模板文件
config.setDirectoryForTemplateLoading(file);
//设置包装器,并将对象包装为数据模型
config.setObjectWrapper(new DefaultObjectWrapper());
//添加数据
Map<String,Object> root=new HashMap<String, Object>();
List list=new ArrayList();
list.add(“tom”);
list.add(“jack”);
root.put("userName",”TOM” );
root.put(“list”,list);
PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("src/templates" + "\\out.html")));
Template template=config.getTemplate("demo.ftl");
//合并数据模型与模板
template.process(root, out);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}catch (TemplateException e) {
e.printStackTrace();
}}}
4.执行main方法:
在src/templates生成out.html文件。
点击文件:
TOM,欢迎你!
tom
jack