freemarker簡單使用

1.導入jar包

<dependency> 
 	<groupId>org.freemarker</groupId> 
 	<artifactId>freemarker</artifactId> 
 	<version>2.3.23</version> 
</dependency>

2.創建模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<#--導入其它模板,擴展名隨意-->
<#include 'title.ifo'>
	
<#--assign可以在模板中定義變量-->
<#assign name="電商項目">
<#--取值-->
${name}

<#--獲取後臺的值-->
${test}

<br>
<#--判斷-->
<#if (money>500)>
	合格
<#else>
	不合格
</#if>

<br>

<#--獲取日期-->
${date?date}<br>
${date?time}<br>
${date?datetime}<br>
<#--定義日期格式-->
${date?string("yyyy 八嘎 MM 雅鹿")}

<br>
<#--遍歷集合-->
<#list list as li>
<#--獲取索引-->
${li_index+1}、 難度: ${li.one}<br>
</#list>
<br>
<#--獲取集合大小-->
一共${list?size}條
<br>


<#--字符串轉JSON-->
<#assign text="{'author':'張飛', 'time':1992}" />
<#assign data=text?eval />
作者: ${data.author} 時間:${data.time?c}<br>

${name!''}

</body>
</html>

3.上代碼

package com.freemarker;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class freeMarkerTem {

public static void main(String[] args) throws Exception {
	//獲取配置文件對象
	Configuration configuration = new Configuration(Configuration.getVersion());
	//指定模板文件所在的位置
	configuration.setDirectoryForTemplateLoading(new File("E:\\eclipsWorkSpace\\freeworkTest\\src\\main\\resources"));
	//設置默認字符集
	configuration.setDefaultEncoding("utf-8");
	//獲取模板
	Template template = configuration.getTemplate("tem.tem");
	//添加數據
	Map map = new HashMap();
	map.put("test","我是測試");
	map.put("money",1000);
	map.put("date",new Date());
	
	List list = new ArrayList();
	Map<String,Object> hashMap = new HashMap();
	hashMap.put("one","簡單");
	Map<String,Object> hashMap1 = new HashMap();
	hashMap1.put("one","中等");
	Map<String,Object> hashMap2 = new HashMap();
	hashMap2.put("one","難");
	
	list.add(hashMap);
	list.add(hashMap1);
	list.add(hashMap2);
	
	map.put("list",list);
	
	//創建模板html
	Writer writer = new FileWriter("D:/freemarker.html");
	
	template.process(map, writer);
	
	writer.close();
}


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