摘自freemarker官网,增加了自己的注释和改动,简单复制和翻译了官网的代码注释,后面有自己根据需要简单改动过的代码。
官网链接为freemarker官网quick start页 。
第一步,创建freemarker配置,应用的生命周期中只要配置一次;
// 创建配置,有特殊需求要指定版本,细节查看java文档
Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
// 指定模板文件地址
cfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
// 指定文字编码
cfg.setDefaultEncoding("UTF-8");
// 错误说明的设置,在网页上则 *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER更好
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
// 不要设置freemarker内部Log,有错误总会看到的
cfg.setLogTemplateExceptions(false);
//将不在范围内的exception指定给TemplateException处理
cfg.setWrapUncheckedExceptions(true);
第二步,创建数据模型;
// 一般数据模型是map格式,也可以是JavaBean
Map<