Freemarker简介 
Freemakrer是用于java中通过向已定义好的模板文件中传递map或JavaBean,从而生成<<文本>>文件的一个工具。网站 :​​http://freemarker.sourceforge.net/​​​
在线文档 :​​http://freemarker.sourceforge.net/docs/index.html​​​
当然,网上也有中文版的pdf文档,也很实用。

书写javaBean
由于我想实验传递javaBean,毕竟Map的使用还是有些麻烦。在这个javaBean中将一般常用类型都包含了。

Java代码
​​

​​


import
import
import
import

public class
private boolean
private int
private
private
private
private
private
}


书写Freemarker的模板文件
其实就是从源码中帖过来小小改动即可。


Java代码
​​

​​


<@license/>

<#list list as bean>
static class
private boolean bolField; <#if bean.bolField>true<#else>false</#if> ${bean.bolField?string("yes","no")}
private int
private BigDecimal bigDecimal; ${bean.bigDecimal!'default value while empty'}
private
private
private
private
}
</#list>


自定义的tag标记
请注意,我使用了一个自定义的tag标记,这个实现也很简单,实现TemplateDirectiveModel即可。


Java代码
​​

​​


public class LicenseDirective implements

public void
throws
"/**\n * @author colin\n */");
}

}


程序主体的代码


Java代码
​​

​​


public class
public static void main(String[] args) throws
new
new
class, "");
"0.####");
"yyyy-MM-dd");
"hh:mm");
"yyyy-MM-dd hh:mm");
// cfg.setBooleanFormat("true,false"); // 无效果

"license", new

new
new SimpleBean(false, 0, null, null, null, null, null));
long now = new
new SimpleBean(true, 1, new BigDecimal("12.345678"),
"freemarker", new Date(now), new Time(now), new

new
"list", list);

// File file = new File("Hello.txt");
// FileOutputStream fos = new FileOutputStream(file);
// Writer out = new OutputStreamWriter(fos);
new

"hello.ftl");
t.process(root, out);
out.flush();
}
}


运行


Java代码
​​

​​


/**
* @author colin
*/
static class
private boolean bolField; false
private int intField; 0
private BigDecimal bigDecimal; default value while
private
private
private
private
}
static class
private boolean bolField; true
private int intField; 1
private BigDecimal bigDecimal; 12.3457
private
private Date date; 2011-03-13
private Time time; 10:22
private Timestamp timestamp; 2011-03-13 10:22
}



注意事项:Freemarker对于null的结果会抛异常,需要自己处理。比如:
! 输出空格
!'the default while empty' 指定一个为空时候的默认值
Freemarker对于boolean的结果会抛异常,需要自己处理。比如:
cfg.setBooleanFormat("true,false"); 在我这边尝试,没有效果,还是需要额外处理boolean的输出
<#if bean.bolField>true<#else>false</#if> 用if else 判断一下,输出自定义的值
${bean.bolField?string(“yes”,”no”)} 转义