接上篇
上篇说道Freemarker会将模板和数据进行整合并且数据相应的结果,应用在web中,有种“页面MVC的感觉”。这篇我们来对freemaker进行封装一下
一般情况下:
用freemarker进行生成操作,步骤
1、创建Configuration(freemarker的)
Configuration cfg = new Configuration();
2、通过configuration获取Template
// 设置了基于classpath加载路径,并且所有的模板文件都放在/ftl中
cfg.setClassForTemplateLoading(TestFreemarker.class, "/ftl");
//获取模板文件,由于已经设置了默认的路径是/ftl,此时hello.ftl就是ftl下的文件
Template temp = cfg.getTemplate("hello.ftl");
3、创建数据文件,非常类似于OGNL,使用map来进行设置
Map<String, Object> root = new HashMap<String, Object>();
root.put("username", "小张");
4、通过模板和数据文件生成相应的输出
temp.process(root, new PrintWriter(System.out));//控制台输出
temp.process(root, new FileWriter("d:/test/hello.html"));//文件输出
看到这种,肯定应该进行简单的封装一下吧
封装类:
private static freeMarkerUtil util;
private static Configuration cfg;
private freeMarkerUtil() {
}
/**
*
* @param pname 模板资源所在的上级目录
* @return 单例模式的构造函数,返回freeMarkerUtil
*/
public static freeMarkerUtil getInstance(String pname) {
if (util == null) {
cfg = new Configuration();
cfg.setClassForTemplateLoading(freeMarkerUtil.class, pname);
util = new freeMarkerUtil();
}
return util;
}
private Template getTemplate(String fname) {
try {
return cfg.getTemplate(fname);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 通过标准输出流输出模板的结果
*
* @param root
* 数据内容
* @param fname
* 模板文件
*/
public void sprint(Map<String, Object> root, String fname) {
try {
getTemplate(fname).process(root, new PrintWriter(System.out));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 文件的输出
*
* @param root
* @param fname
* @param outpath
*/
public void fprint(Map<String, Object> root, String fname, String outpath) {
try {
getTemplate(fname).process(root, new FileWriter(outpath));
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
调用:
public class TestFreemarkerUtil {
private freeMarkerUtil util = freeMarkerUtil.getInstance("/ftl");
private Map<String, Object> root = new HashMap<String, Object>();
private String fn = "d:/test/freemarker/";
@Before
public void setUp() {
User user = new User("admin", "管理员", 25);
Group group = new Group("财务处", 1);
root.put("group", group);
root.put("user", user);
}
@Test
public void testModel() {
util.sprint(root, "helloModel01.ftl");
util.fprint(root, "helloModel01.ftl", fn + "userGroup.html");
}
}
结果: