https://blog.csdn.net/candy_rainbow/article/details/74225360
配置文件写好了之后就可以来写FreemarkerUtil了,这个工具类主要就是将传入的数据模型生成静态页面:
private static String staticPagePath = "C:/Users/hao/Desktop/staticPages";
/**
* @param data 数据模型
* @param templatePath 模板路径 "WEB-INF/templates"
* @param templateFileName 模板文件名 "main.html"
* @param staticPageName 生成的静态文件的文件名
*/
public static void createStaticPage(Configuration cfg,HttpServletRequest request,String staticPageName ,Map<String, Object> data, String templatePath, String templateFileName) {
try {
cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);// 设置标签
cfg.setServletContextForTemplateLoading(request.getServletContext(),templatePath);// 设置临时加载目录。
cfg.setDefaultEncoding("UTF-8");
cfg.setNumberFormat("#");
Template temp = cfg.getTemplate(templateFileName);// 获取模板对象
Writer out = new OutputStreamWriter(new FileOutputStream(staticPagePath+"/"+staticPageName+(new Date()).getTime()+".html"), "UTF-8");
temp.process(data, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
还有一个工具方法是判断文件是否已经存在:
/**
* @param request
* @param filePath 文件存放的路径
* @param fileName 文件的名称,需要扩展名
* @author HuifengWang
* @return
*/
public static Map<String,Object> htmlFileHasExist(HttpServletRequest request,String filePath,
String fileName) {
Map<String,Object> map = new HashMap<String,Object>();
String htmlPath = request.getSession().getServletContext() .getRealPath(filePath) + "/" + fileName;
File htmlFile = new File(htmlPath);
if(htmlFile.exists()){
map.put("exist", true);
}else{
map.put("exist",false);
}
return map ;
}
OK,以上就是FreemarkerUtil的内容,原理很简单。
最后生成的页面:
Demo的目录结构如下:
当然,以后要查询页面的时候涉及到了检索,我们用的是Lucene全文检索,后文在说。