这几天在搞一个利用freemarker和java生成静态页面的东西,经过百度和自己的调试终于搞定,现在总结出核心代码分享。
/**
* 生成静态页面主方法
*
* @param context
* ServletContext
* @param data
* 一个Map的数据结果集
* @param templatePath
* ftl模版路径
* @param targetHtmlPath
* 生成静态页面的路径
*/
public static void crateHTML(ServletContext context,
Map<String, Object> data, String templatePath, String targetHtmlPath) {
// 加载模版
freemarkerCfg.setServletContextForTemplateLoading(context, "/");
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
String filePath = ServletActionContext.getServletContext().getRealPath(
"/static");
File file = new File(filePath);
if(!file.exists() || !file.isDirectory()){
file.mkdir();
}
File f = new File(file,"/all_css");
if(!f.exists() || !f.isDirectory()){
f.mkdir();
}
try {
freemarkerCfg.setDirectoryForTemplateLoading(new File(filePath));
// 设置包装器,并将对象包装为数据模型
freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
// 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
// 否则会出现乱码
Template template = freemarkerCfg
.getTemplate(templatePath, "UTF-8");
template.setEncoding("UTF-8");
// 静态页面路径
String htmlPath = filePath + "/" + 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();
}
}
/**
* 生成友情链接的静态页cuxiao.html
*
* @param context
* @param data
*/
public static void createIndexFriendLink(ServletContext context,
Map<String, Object> data) {
try {
//cuxiao.ftl是项目中建立的ftl文件,cuxiao.html是生成的静态页面名
return crateHTML(context, data, "/cuxiao.ftl", "cuxiao.html");
} catch (Exception e) {
e.printStackTrace();
}
}
最后调用方法,private Map<String, Object> pList = new HashMap<String, Object>();
List list = new ArrayList();
pList.put("list",list);
HttpServletRequest request = ServletActionContext.getRequest();
pList.put("JspTaglibs", new TaglibFactory(request.getSession()
.getServletContext()));
this.createIndexFriendLink(
ServletActionContext.getServletContext(), pList);
//页面介绍map时一定要与pList中的key一致