public class FreemarkerTest {
private final Log logger=LogFactory.getLog(getClass());
private Configuration freemarke_cfg=null;
protected Configuration getFreeMarkerCFG(String sTemplateFilePath){
if(null==freemarke_cfg){
freemarke_cfg=new Configuration();
freemarke_cfg.setEncoding(Locale.CHINA, "UTF-8");
//基于类路径的模版加载器
freemarke_cfg.setClassForTemplateLoading(this.getClass (), "/websiteroot/freemarker");
try{
freemarke_cfg.setDirectoryForTemplateLoading(new File (sTemplateFilePath));
}catch (Exception e) {
e.printStackTrace();
}
}
return freemarke_cfg;
}
/**
*生成静态文件
*@param templatePath:模板路径
*@param templateFileName:模板名称
*@param propMap:存放数据模型的Map
*@param htmlFilePath:生成HTML页面的存放路径
*@param htmlFileName:生成html页面的名称
* */
public boolean geneHtmlFile(String templatePath,String templateFileName,Map propMap,String htmlFilePath,String htmlFileName){
try{
Template t=getFreeMarkerCFG(templatePath).getTemplate(templateFileName);
t.setEncoding("UTF-8");
creatDirs(htmlFilePath);
File afile = new File(htmlFilePath+"/"+htmlFileName);
//设置生成的文件编码为UTF-8
//服务器不支持UTF-8格式HTML时候使用ANSI格式HTML文件,即系统默认编码
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(afile),"UTF-8"));
t.process(propMap, out);
}catch(TemplateException e){
logger.error("Error "+templateFileName,e);
return false;
}catch(IOException e){
logger.error("Error "+htmlFileName,e);
return false;
}
return true;
}
public static boolean creatDirs(String path){
File aFile = new File(path);
if(!aFile.exists()){
return aFile.mkdirs();
}else{
return true;
}
}
}