轉至:http://blog.sina.com.cn/s/blog_667ac0360102eaz8.html
// 測試程序
package myTest;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FtlTest {
public static void main(String[] args) throws Exception {
Map<String, Object> dataMap = getModel_1();
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setClassForTemplateLoading(FtlTest.class, "/ftl/");
Template template = configuration.getTemplate("test.ftl");
template.process(dataMap, new BufferedWriter(new OutputStreamWriter(System.out)));
dataMap = getModel_2();
template.process(dataMap, new BufferedWriter(new OutputStreamWriter(System.out)));
dataMap = getModel_3();
template.process(dataMap, new BufferedWriter(new OutputStreamWriter(System.out)));
}
public static Map<String, Object> getModel_1() {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("data_string", "string");
dataMap.put("data_int", 3);
dataMap.put("data_float", 3.333);
dataMap.put("data_boolean", true);
dataMap.put("data_date", new Date());
return dataMap;
}
public static Map<String, Object> getModel_2() {
Map<String, Object> dataMap = new HashMap<String, Object>();
return dataMap;
}
public static Map<String, Object> getModel_3() {
Map<String, Object> dataMap = new HashMap<String, Object>();
SimpleDateFormat df = new SimpleDateFormat("yyyy");
Date year = null;
try {
year = df.parse("2013");
} catch (ParseException e) {
throw new RuntimeException(e);
}
dataMap.put("data_date", year);
return dataMap;
}
}
// 模板
<#escape x as x?default("")>
數據類型測試
data_string=${data_string}
data_int=${data_int}
data_float=${data_float}
data_boolean=<#if data_boolean?exists>${data_boolean?string}</#if>
data_date=<#if data_date?exists>${data_date?string('yyyy-MM-dd')}</#if>
</#escape>
// 輸出
數據類型測試
data_string=string
data_int=3
data_float=3.333
data_boolean=true
data_date=2013-09-25
數據類型測試
data_string=
data_int=
data_float=
data_boolean=
data_date=
數據類型測試
data_string=
data_int=
data_float=
data_boolean=
data_date=2013-01-01
說明:freemarker不會處理null數據,null會報錯;使用<#escape標簽,來為所有的插值做轉換;轉換調用了default內置函數,將null填充為“”空字符串;這樣,如果在插值處要調用內置函數,就應該先使用<#if標簽先判斷是否存在了;布爾型、日期型默認不會自動轉換為字符串,需要內置函數處理,在調用內置函數前要做是否存在的驗證;最后,以上測試,日期型類型轉換是根據Date類型來轉換的,string內置函數可以比較靈活地使用自定義格式顯示;