freemarker模板技术(一)
easyjava吧
全部回复
仅看楼主
level 8
噢丶Right 楼主
package org.act.freemarkers;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;import javax.servlet.ServletContext;import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;/************
* freemarker模板生成静态页
* @author shenkunlin
* date 2013/8/5
*/
public class FreemarkerUtils { private static FreemarkerUtils freemarker = null; private FreemarkerUtils() {
} public static FreemarkerUtils instatnceFreemarker() {
if (freemarker == null) {
freemarker = new FreemarkerUtils();
}
return freemarker;
} // 获取模板
public Template getTemplate(ServletContext context, String templateName) {
// Configuraction
Configuration cfg = new Configuration();
// 加载模板路劲
cfg.setServletContextForTemplateLoading(context, File.separator
+ "ftl"); // 设置包装器
cfg.setObjectWrapper(new DefaultObjectWrapper()); // 设置默认编码
cfg.setDefaultEncoding("UTF-8"); Template template = null;
try {
// 获取指定模板
template = cfg.getTemplate(templateName);
} catch (IOException e) {
e.printStackTrace();
}
return template;
} // 生成静态页
public void writeHtml(Map<?, ?> rootMap, ServletContext context,
String templateName, String htmlName, String htmlPath) {
Template template = this.getTemplate(context, templateName);
// 合并数据模型与模板
try {
template.setEncoding("UTF-8");
FileOutputStream fos = new FileOutputStream(htmlPath
+ File.separator + htmlName);
Writer out = new OutputStreamWriter(fos, "UTF-8");
template.process(rootMap, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
2013年08月21日 03点08分 1
level 9
2013年08月21日 04点08分 2
level 8
2013年08月24日 07点08分 3
level 8
2013年08月24日 07点08分 4
1