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");
	}

}


結果:







發佈了145 篇原創文章 · 獲贊 183 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章