freemarker生成静态页面

时间:2022-11-13 08:37:32

1.概述

今天尝试将网站首页静态化,使用的freemarker,用ftl文件作为模板,传入从数据库中查询的数据。

2,代码

public static boolean createHTML(ServletContext context,
Map<String, Object> data, String templatePath, String targetHtmlPath) {
Configuration freemarkerCfg = new Configuration();
// 加载模版
freemarkerCfg.setServletContextForTemplateLoading(context, "/");
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
freemarkerCfg.setNumberFormat("0.######");
try {
// 指定模版路径
Template template = freemarkerCfg
.getTemplate(templatePath, "UTF-8");
template.setEncoding("UTF-8");
// 静态页面路径
String htmlPath = context.getRealPath("/templates/shop/html/") + "/"
+ targetHtmlPath;
File htmlFile = new File(htmlPath);
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(htmlFile), "UTF-8"));
// 处理模版
template.process(data, out);
out.flush();
out.close();
} catch (Exception e) {

e.printStackTrace();
return false;
}
return true;

}

注意:1,参数ServletContext context,servlet上下文,在spring中获得方式:

WebApplicationContext webApplicationContext = ContextLoader
.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext
.getServletContext();

2,参数Map<String, Object> data 数据

3,参数templatePath:模板文件路劲,targetHtmlPath生成文件路径

4,如果模板文件使用<#include "filepath">,找不到文件,可使用freemarkerCfg.setServletContextForTemplateLoading(context, setPath);设置模板文件加载路径。

最后的路经应该是setPath + filepath。

5,我在页面放入数字123456,静态化之后得到的是123,456,必须要设置freemarkerCfg.setNumberFormat("0.######");才能得到想要的结果。想必有其他解析结果显示问题,也可以通过设置cfg来解决。

6,ftl模板中有注释(<!-- -->)的时候生成错误,不能确定是什么原因