freemark初體驗之helloWorld

這段時間做了一個根據模板生成html頁面的功能,是自己採用string的replace來實現替換標籤的。在做之前是準備使用freemaker,不過由於某些原因只好採用自己替換的形式,這裏在寫一次使用freemarker的示例。

因爲項目採用maven,加入依賴

<dependency>
     <groupId>freemarker</groupId>
     <artifactId>freemarker</artifactId>
     <version>2.3.1</version> 
</dependency>
hello.flt的內容 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
	hello,${user}
</body>
</html>

代碼如下:

public static void main(String[] args) throws IOException, TemplateException {
		//獲取路徑
		String context=Config.GetFileDirect();
		if (!StringUtils.endsWith(context, "/") && !StringUtils.endsWith(context, "\\"))
			context += '/';
		//根據模板生成文件
		Configuration conf=new Configuration();
		conf.setDirectoryForTemplateLoading(new File(context+"template/"));
		conf.setSetting("defaultEncoding", "UTF-8");  
        Template temp = conf.getTemplate("hello.ftl"); 
        
        Map<String,Object> datas = new HashMap<String,Object>();  
        datas.put("user", "遊客");
        String outPath=context+"hello.html";
        File outFile=new File(outPath);
        Writer out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        temp.process(datas, out);
}
運行後生成的html 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
	hello,遊客
</body>
</html>

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