生成靜態文件的類:
// 加載模版目錄,FreeMarker支持多種模板裝載方式,可以查看API文檔,都很簡單:路徑,根據Servlet上下文,classpath等等
freemarkerCfg.setServletContextForTemplateLoading(context, "/ftl"); //WebRoot下的ftl目錄,放freemarker的模板
freemarkerCfg.setClassForTemplateLoading(CreateHtmlPage.class, "/htmlskin"); //htmlskin是放在classpath下的一個目錄
freemarkerCfg.setDirectoryForTemplateLoading(new File("/where/you/store/templates"));
package pagehtml;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class CreateHtmlPage {
/**
* 生成靜態頁面主方法
*
* @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) {
Configuration freemarkerCfg = new Configuration();
// 加載模版
freemarkerCfg.setServletContextForTemplateLoading(context, "/ftl");
freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
try {
// 指定模版目錄
Template template = freemarkerCfg.getTemplate(templatePath, "UTF-8");
template.setEncoding("UTF-8");
// 靜態頁面路徑
String htmlPath = context.getRealPath("/html") + "/" + 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();
}
}
/**
* 生成類型列表靜態頁
*
* @param context
* @param data
*/
public static void createIndexFriendLink(ServletContext context, Map<String, Object> data) {
crateHTML(context, data, "/categorylist.ftl", "categorylist.html");
}
}
/**
* 生成友情鏈接靜態頁html
*
* @return
*/
public ActionForward createViewHtml(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
// 獲取頁面表單提交的值
CategoryForm categForm = (CategoryForm) form;
Category category = new Category();
BeanUtils.copyProperties(category, categForm);
// 調用業務邏輯操作
TableManagerFactory tableManagerFactory = new TableManagerFactory();
ITableManager manager = (ITableManager) tableManagerFactory.createTableDao("jdbc.CategoryDao");
category = (Category) manager.view(category);
// 準備數據
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("category", category);
// 調用靜態頁面方法
ServletContext context = request.getSession().getServletContext();
CreateHtmlPage.createIndexFriendLink(context, data);
return mapping.findForward("viewlisthtml");
} catch (Exception e) {
e.printStackTrace();
return mapping.findForward("viewlisthtml");
}
}