Freemarker模板應用

FreeMarker是一個用Java語言編寫的模板引擎,它基於模板來生成文本輸出。FreeMarker與Web容器無關,即在Web運行時,它並不知道Servlet或HTTP。它不僅可以用作表現層的實現技術,而且還可以用於生成XML,JSP或Java 等。

一、FreeMarker主要部分

FreeMarker的模板文件並不比HTML頁面複雜多少,FreeMarker模板文件主要由如下4個部分組成: 
1,文本:直接輸出的部分 
2,註釋:<#-- ... -->格式部分,不會輸出 
3,插值:即${...}或#{...}格式的部分,將使用數據模型中的部分替代輸出 
4,FTL指令:FreeMarker指定,和HTML標記類似,名字前加#予以區分,不會輸出 
下面是一個FreeMarker模板的例子,包含了以上所說的4個部分 

<html><br> 
<head><br> 
<title>Welcome!</title><br> 
</head><br> 
<body><br> 
<#-- 註釋部分 --><br> 
<#-- 下面使用插值 --> 
<h1>Welcome ${user} !</h1><br> 
<p>We have these animals:<br> 
<u1><br> 
<#-- 使用FTL指令 --> 
<#list animals as being><br> 
   <li>${being.name} for ${being.price} Euros<br> 
<#list><br> 
<u1><br> 
</body><br> 
</html> 

二、Freemarker模板應用事例

------------------普通變量獲取-------------------
${user}
---------獲取Map中屬性--------------
${latestProduct.url}
${latestProduct.name}
-------if判斷指令-------
<#if target??>
    xxxx
<#else>
   xxxx
</#if>

<#if str == "success">
    xxx
</#if>
<#if str !== "error">
xxx
</#if>

三、自動生成代碼應用

1.在lib中加入freemarker.jar的包

2.在文件templates創建一個文件 test.ftl

內容爲:

   ${name},你好,${msg}

3.通過兩個類完成Freemarker寫入,具體看類中的使用
ResourceText.java   

public class ResourceText {
	
	//填充數據模型
	public void paddingdata(){
		String htmlTemplateNa = "test.ftl";
		Map<String,Object> variables =new HashMap<String,Object>();
	  	variables .put("name", "chenhaibin");
	  	variables .put("msg", "歡迎使用FreeMarker!");
		generateHtmlContent(htmlTemplateNa ,variables)
	}
	
	//取htmltemp所在路徑	
	public String getPdfPath(){
		String path = null;
		try {
			path = ctx.getResource("classpath:templates").getFile().getPath()+File.separator;
		} catch (IOException e) {
			logger.info("取模板所在路徑報錯:=====get pdfTemplate path error....");
			e.printStackTrace();
		}
		logger.info("path:"+path+"####################");
		return path;
	}
	
	public String generateHtmlContent(String htmlTemplateNa, Map<String,Object> variables) throws IOException, TemplateException{     
	        BufferedWriter writer = null;   //緩衝字符輸出流
	        String htmlContent = "";
	        try{
			//用Configuration實例生成Template實例,同時加載指定的模板文件
	        	Configuration config = FreemarkerConfiguration.getConfiguation(pdfUtil.getPdfPath());
	        	Template tp = config.getTemplate(htmlTemplateNa);     
	        	StringWriter stringWriter = new StringWriter();       
	        	writer = new BufferedWriter(stringWriter);  
	               //writer = new BufferedWriter(new OutputStreamWriter(System.out));
	     	
	        	tp.setEncoding("UTF-8");       
	        	tp.process(variables, writer);  
	        	htmlContent = stringWriter.toString();     
	        	writer.flush();       
	        	logger.debug("step 模板:"+htmlTemplateNa+" 生成html string 成功");
	        }finally{
	        	if(writer!=null)
	        		writer.close();     
	        }
	        return htmlContent;     
	    } 
	}

}

FreemarkerConfiguration.java
public class FreemarkerConfiguration {

	private static Configuration config = null;

	public static Configuration getConfiguation(String path) {
		if (config == null) {
			setConfiguation(path);
		}
		return config;
	}
	//創建Configuration實例,該實例負責管理FreeMarker的模板加載路徑
	private static void setConfiguation(String path) {
		config = new Configuration();
		try {
			config.setDirectoryForTemplateLoading(new File(path));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

總結:

//Freemarker的核心代碼就四句:
/1、Configuration cf = new Configuration();//實例化Configuration 
/2、cf.setDirectoryForTemplateLoading(new File(D:/myspace/freemarker/resource/template/));//爲模板加載設置目錄
/3、Template temp = cf.getTemplate("codeModel.ftl");//獲取模板文件
/4、//設置字符串緩衝區,並寫入到模板文件中
	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	temp.process(map, bw);




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章