ftl模板

ftl模版文件生成静态页面

2012-02-16 15:48:40| 分类: coding |字号 订阅
action部分代码:
public class Cretehtml {
private Map<String,Object> root=new HashMap<String, Object>();
//生成静态化页面
public String execute() throws Exception {
//将用到的变量存放到root
root.put("name", member.getName());
root.put("userid", member.getUserId());
root.put("age", member.getAge());
//静态页面的完整路径
String str=ServletActionContext.getServletContext().getRealPath("/")+"/statichtml/index.html";
File file=new File(str);
//如果静态文件存在,则删除静态页面之后重新生成
if(file.isFile()&&file.exists()){
file.delete();
}
str=null;//释放资源
if(file!=null)file=null;
StaticFreemarker.createHTML(ServletActionContext.getServletContext(), root, "sy/index.ftl", "/statichtml/index.html");
return "firstpage";
}
}
StaticFreemarker 类:
/**
*
* @param context
* @param data 传送的数据
* @param templatePath ftl路径
* @param targetHtmlPath 生成html文件的路径
*/
class StaticFreemarker {
public static void createHTML(ServletContext context,Map<String,Object>data,String templatePath,String targetHtmlPath) {
Configuration cfg = new Configuration();
cfg.setServletContextForTemplateLoading(context, "/WEB-INF/template/");//ftl的基本路径
cfg.setEncoding(Locale.getDefault(), "utf-8");//设置编码
Writer out = null;
try {
Template t = cfg.getTemplate(templatePath, "utf-8");//获取模板文件
t.setEncoding("utf-8");
//静态页面路径设置
String htmlPath = context.getRealPath("/")+"/"+targetHtmlPath;
File htmlFile = new File(htmlPath);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile),"utf-8"));
t.process(data, out);//将数据写到静态页面
} catch (Exception e) {
e.printStackTrace();
} finally{
if(out != null){
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值