FreeMarker学习(二)

来源:互联网 发布:网络挖矿是啥意思 编辑:程序博客网 时间:2024/05/21 09:36

接上篇

  上篇说道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 blocke.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/";@Beforepublic void setUp() {User user = new User("admin", "管理员", 25);Group group = new Group("财务处", 1);root.put("group", group);root.put("user", user);}@Testpublic void testModel() {util.sprint(root, "helloModel01.ftl");util.fprint(root, "helloModel01.ftl", fn + "userGroup.html");}}


结果:







0 0
原创粉丝点击