简介
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
FreeMarker是免费的,基于Apache许可证2.0版本发布。其模板编写为FreeMarker Template Language(FTL),属于简单、专用的语言。需要准备数据在真实编程语言中来显示,比如数据库查询和业务运算, 之后模板显示已经准备好的数据。在模板中,主要用于如何展现数据, 而在模板之外注意于要展示什么数据 。
使用
1、 安装 freemarker eclipse 编辑插件
将 “freemarker_eclipseplugin” 复制 eclipse 的 dropins 文件夹 ,重启开发工具
2、 编辑 freemarker 的模板文件
通常模板文件 放在 WEB-INF 下 或者 classes 下
3、 编写测试代码
public String showDetail() throws Exception {
// 先判断 id 对应html 是否存在,如果存在 直接返回
String htmlRealPath = ServletActionContext.getServletContext()
.getRealPath("/freemarker");
File htmlFile = new File(htmlRealPath + "/" + model.getId() + ".html");
// 如果html文件不存在 ,查询数据库,结合freemarker模板生成 页面
if (!htmlFile.exists()) {
Configuration configuration = new Configuration(
Configuration.VERSION_2_3_22);
configuration.setDirectoryForTemplateLoading(new File(
ServletActionContext.getServletContext().getRealPath(
"/WEB-INF/freemarker_templates")));
// 获取模板对象
Template template = configuration
.getTemplate("promotion_detail.ftl");
// 动态数据
Promotion promotion = WebClient
.create(Constants.BOS_MANAGEMENT_URL
+ "/bos_management/services/promotionService/promotion/"
+ model.getId()).accept(MediaType.APPLICATION_JSON)
.get(Promotion.class);
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("promotion", promotion);
// 合并输出
template.process(parameterMap, new OutputStreamWriter(
new FileOutputStream(htmlFile), "utf-8"));
}
// 存在 ,直接将文件返回
ServletActionContext.getResponse().setContentType(
"text/html;charset=utf-8");
FileUtils.copyFile(htmlFile, ServletActionContext.getResponse()
.getOutputStream());
return NONE;
}