freemarker2
2022-07-18
freemarker2
freemarker后台
freemarker简单环境搭建
-
导入maven依赖
org.freemarker freemarker 2.3.9 -
创建Freemarker工具类,获取模板对象
public class FreemarkerUtil {
/**- 获取模板对象
- @param name
- @return
/
public Template getTemplate(String name){
Template temp = null;
try{
//获取Configuration配置对象
Configuration cfg = new Configuration();
//设置模板加载的路径
cfg.setDirectoryForTemplateLoading(new File("F:\mhn\Test\src\main\webapp\ftl"));
//获取模板对象
temp = cfg.getTemplate(name);
}catch (IOException e){
e.printStackTrace();
}
return temp;
}
/* - 控制台输出文件内容
- @param name
- @param rootMap 名字和对应的属性(object)
*/
public void print(String name, Map<String, Object> rootMap) {
try {
// 通过Template类可以将模板文件输出到相应的文件
Template temp = this.getTemplate(name);
//打印到控制台
temp.process(rootMap, new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
- 将替换后的模板内容输出到文件
- @param name ftl模板的名字
- @param rootMap 数据
- @param outFile 输出的html文件名
*/
public void fprint(String name, Map<String, Object> rootMap, String outFile) {
FileWriter out = null;
try {
//获取要保存输出的文件路径
out = new FileWriter(new File("F:\马皓楠\test\freemarker\"
- outFile));
Template template = this.getTemplate(name);
template.process(rootMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
-
写测试类
public class TestFreemarker {
private FreemarkerUtil freemarkerUtil;
private Map<String, Object> rootMap = null;
@Before
public void setUp() {
freemarkerUtil = new FreemarkerUtil();
rootMap = new HashMap<String, Object>();
}@Test
public void test01() {
// 填充数据
rootMap.put("username", "王三毛");
// 打印到控制台
freemarkerUtil.print("demo1.ftl", rootMap);
// 输出到文件
freemarkerUtil.fprint("demo1.ftl", rootMap, "demo1.html");
}
} -
思路分析
freemarker是第三方jar包,需要导入依赖包
先创建Configuration配置对象
然后利用cfg.setDirectoryForTemplateLoading(new File())来加载模板所在的路径
然后cfg.getTemplate()获取模板对象fprint()方法,利用template.process(Object dataModel, Writer out)方法,将数据和模板转换为html文件