FreeMarker学习(二)

接上篇

  上篇说道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");
	}

}


结果:







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值