package auh.server;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* FreeMarker 生成静态html
* @author 可可
* @param 默认模板文件放在web根目录下的/WEB-INF/template
* @param sRootDir 生成的静态页面的根路径,默认为web的根路径,可以通过setSRootDir设置
*/
public class MakeFile {
private Configuration freemarker_cfg;
private String sRootDir;
public MakeFile(){
this.freemarker_cfg = new Configuration();
ServletContext con=ServletActionContext.getServletContext();
this.freemarker_cfg.setServletContextForTemplateLoading(con,"/WEB-INF/template");
//String templatePath=sRootDir+"/WEB-INF/template";
//freemarker_cfg.setDirectoryForTemplateLoading(new File(templatePath));//用路径装载
//freemarker_cfg.setClassForTemplateLoading(this.getClass(), "/htmlskin");//用classpath装载,htmlskin是放在classpath下的一个目录
this.freemarker_cfg.setNumberFormat("0.##########");//设置数字转换数字串的格式
this.freemarker_cfg.setEncoding(Locale.getDefault(), "UTF-8");
this.freemarker_cfg.setObjectWrapper(new DefaultObjectWrapper());
this.sRootDir =con.getRealPath("/");
}
/**
* 生成静态文件
* @param templateFileName 模板文件名,例如"view.ftl"
* @param root 用于处理模板的属性Object映射
* @param htmlFilePath 要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"
* @param htmlFileName 要生成的文件名,例如 "1.html"
* @return boolean 是否成功
*/
public boolean geneHtmlFile(String templateFileName,Map<String,Object> root, String htmlFilePath,String htmlFileName )
{
try{
Template t = this.freemarker_cfg.getTemplate(templateFileName);
creatDirs(sRootDir,htmlFilePath); //如果根路径存在,则递归创建子目录
File fileName = new File(sRootDir +"/" +htmlFilePath + "/" + htmlFileName);
Writer out = new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8");
t.process(root, out);//生成静态文件
}
catch (TemplateException e)
{
System.out.println(e);
return false;
}
catch (IOException e)
{
System.out.println(e);
return false;
}
return true;
}
/**
* 创建多级目录
* @param aParentDir String
* @param aSubDir 以 / 开头
* @return boolean 是否成功
*/
public static boolean creatDirs(String aParentDir, String aSubDir)
{
File aFile = new File(aParentDir);
if (aFile.exists())
{
File aSubFile = new File(aParentDir + aSubDir);
if (!aSubFile.exists())return aSubFile.mkdirs();
else return true;
}
else return false;
}
/**
* 设置静态文件的存放的根路径
* @param rootDir 应为绝对路径。
*/
public void setSRootDir(String rootDir) {
sRootDir = rootDir;
}
public String getSRootDir() {
return sRootDir;
}
}