Freemarker生成静态html示例

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.views.JspSupportServlet;
import org.apache.struts2.views.freemarker.FreemarkerManager;

import com.opensymphony.xwork2.ActionSupport;
import com.sz7road.web.common.util.ServiceLocator;
import com.sz7road.web.service.TempHtmlService;

import freemarker.ext.jsp.TaglibFactory;
import freemarker.ext.servlet.HttpRequestHashModel;
import freemarker.ext.servlet.ServletContextHashModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class TempHtmlAction extends ActionSupport {

	private static final Logger logger = LogManager.getLogger(GeneHtmlFileAction.class);
	
	private Configuration freemarker_cfg = null;
	
	public String tempIndixHtml(){
		TempHtmlService tempHtmlService = ServiceLocator.getTempHtmlrService();
		String sGeneFilePath = "";
		String sFileName = "index.html";
		try {
			Map<String, Object> dataMap = tempHtmlService.createIndex();
			geneHtmlFile("temp/index.ftl", dataMap, sGeneFilePath, sFileName);
		} catch (Exception e) {
			logger.error("Index Html Error:" + e.getMessage(), e);
		}
		return SUCCESS;
	}	
	/**
	 * 获取freemarker的配置. freemarker本身支持classpath,目录和从ServletContext获取.
	 */
	protected Configuration getFreeMarkerCFG() {
		if (null == freemarker_cfg) {
			File templateFile = new File(ServletActionContext
					.getServletContext().getRealPath("/") + "WEB-INF/template");
			freemarker_cfg = new Configuration();
			try {
				freemarker_cfg.setDirectoryForTemplateLoading(templateFile);
				freemarker_cfg.setEncoding(Locale.CHINA, "UTF-8");
			} catch (IOException e) {
				logger.error("Get tempalte error", e);
			}
		}

		return freemarker_cfg;
	}

	/**
	 * 生成静态文件.
	 * 
	 * @param templateFileName
	 *            模板文件名,相对htmlskin路径,例如"/tpxw/view.ftl"
	 * @param propMap
	 *            用于处理模板的属性Object映射
	 * @param htmlFilePath
	 *            要生成的静态文件的路径,相对设置中的根路径,例如 "/tpxw/1/2005/4/"
	 * @param htmlFileName
	 *            要生成的文件名,例如 "1.htm"
	 */
	public boolean geneHtmlFile(String templateFileName,
			Map<String, Object> propMap, String htmlFilePath,
			String htmlFileName) {
		// @todo 从配置中取得要静态文件存放的根路径:需要改为自己的属性类调用
		//String sRootDir = "/var/www/ddtank/web";
		String sRootDir = ServletActionContext.getRequest().getRealPath("/webpage");
		try {
			if (propMap == null) {
				propMap = new HashMap<String, Object>();
			}
			ServletContext servletContext = ServletActionContext
					.getServletContext();
			// data.put("JspTaglibs", new TaglibFactory(servletContext));
			FreemarkerManager freemarkerManager = new FreemarkerManager();
			Configuration configuration = freemarkerManager
					.getConfiguration(servletContext);
			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			ServletContextHashModel servletContextModel = (ServletContextHashModel) servletContext
					.getAttribute(".freemarker.Application");
			if (servletContextModel == null) {
				GenericServlet servlet = JspSupportServlet.jspSupportServlet;
				if (servlet != null) {
					servletContextModel = new ServletContextHashModel(servlet,
							configuration.getObjectWrapper());
					servletContext.setAttribute(".freemarker.Application",
							servletContextModel);
					TaglibFactory taglibs = new TaglibFactory(servletContext);
					servletContext.setAttribute(".freemarker.JspTaglibs",
							taglibs);
				}
			}
			HttpRequestHashModel requestModel = (HttpRequestHashModel) request
					.getAttribute(".freemarker.Request");
			if ((requestModel == null)
					|| (requestModel.getRequest() != request)) {
				requestModel = new HttpRequestHashModel(request, response,
						configuration.getObjectWrapper());
				request.setAttribute(".freemarker.Request", requestModel);
			}
			propMap.put("Application", servletContextModel);
			propMap.put("Request", requestModel);
			propMap.put("Session", ServletActionContext.getRequest()
					.getSession());
			propMap.put("JspTaglibs",
					new TaglibFactory(ServletActionContext.getServletContext()));

			Template t = getFreeMarkerCFG().getTemplate(templateFileName);

			// 如果根路径存在,则递归创建子目录
			creatDirs(sRootDir, htmlFilePath);
			File afile = new File(sRootDir + "/" + htmlFilePath + "/"
					+ htmlFileName);
			Writer out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(afile), "UTF-8"));

			t.process(propMap, out);
			out.flush();
			out.close();

		} catch (TemplateException e) {
			logger.error("Error while processing FreeMarker template "
					+ templateFileName, e);
			return false;
		} catch (IOException e) {
			logger.error("Error while generate Static Html File "
					+ htmlFileName, 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()) {
			aFile.mkdirs();
		}
		File aSubFile = new File(aParentDir + aSubDir);
		if (!aSubFile.exists()) {
			return aSubFile.mkdirs();
		} else {
			return true;
		}
	}

}
 

相关推荐