生成静态文件的类:
// 加载模版目录,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");
}
}