java中不乏優(yōu)秀的模板引擎,Velocity,mvel,FreeMarker等。在構(gòu)建框架的時候,通常可以拿來即用,但我們需要控制它。最近需要一個數(shù)據(jù)準(zhǔn)備的框架,便選擇了FreeMarker,F(xiàn)reeMarker使用起來很簡單,data+template=out.今天主要寫一下其中template加載組件TemplateLoader
TemplateLoader的實(shí)現(xiàn)作為一個模板文件加載的抽象,自然不能限制模板來自何方,在FreeMarker中由幾個主要的實(shí)現(xiàn)類來體現(xiàn),這些TemplateLoader是可以獨(dú)立使用的,Webapp需要Servlet環(huán)境。當(dāng)然你可以實(shí)現(xiàn)自己的TemplateLoader.
剛開始總覺得StringTemplateLoader簡單,其實(shí)挺麻煩,而且也無大用。
@Testpublic void testStringTL() throws IOException {StringTemplateLoader stl = new StringTemplateLoader();String template = "${key}";stl.putTemplate("hello", template);Object source = stl.findTemplateSource("hello");Reader reader = stl.getReader(source, "utf-8");String dest = IOUtils.toString(reader);Assert.assertEquals(template, dest);}MultiTemplateLoaderTemplateLoader是可以多種類型,同種類型組合起來使用的,查詢順序按照數(shù)組的順序優(yōu)先。
@Testpublic void testMultiTL() throws IOException {TemplateLoader ctl = new ClassTemplateLoader(TemplateLoaderTest.class,"/");TemplateLoader ftl1 = new FileTemplateLoader(new File(System.getPRoperty("user.dir")));MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] {ftl1,ctl });Object source = mtl.findTemplateSource("test.ftl");Reader reader = mtl.getReader(source, "utf-8");String dest = IOUtils.toString(reader);Assert.assertEquals("${hello}", dest);}通常在Configuration中使用,才能方便的處理FreeMarker的表達(dá)式@Testpublic void testInConfiguration() throws IOException {Configuration configuration = new Configuration(Configuration.VERSION_2_3_21);configuration.setDefaultEncoding("utf-8");TemplateLoader ctl = new ClassTemplateLoader(TemplateLoaderTest.class,"/");TemplateLoader ftl1 = new FileTemplateLoader(new File(System.getProperty("user.dir")));MultiTemplateLoader mtl = new MultiTemplateLoader(new TemplateLoader[] {ftl1,ctl });configuration.setTemplateLoader(mtl);//configuration.getTemplate("test.ftl").process(data, out);}其它緩存模板加載通常是耗費(fèi)資源的,默認(rèn)是開啟緩存的,緩存的實(shí)現(xiàn),是否使用緩存取決于你
configuration.setCacheStorage(new freemarker.cache.NullCacheStorage());configuration.clearTemplateCache();
|
新聞熱點(diǎn)
疑難解答