freemarker静态化例子

package freemark;


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.Locale;
import java.util.Map;


import javax.servlet.ServletContext;


import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class ToHtml {
public static void toHtml(ServletContext context,Map<String, Object> data,String templatePath,String targetHtmlPath){
Configuration configuration=new Configuration();
//加载模板
configuration.setServletContextForTemplateLoading(context, "/");
configuration.setEncoding(Locale.getDefault(), "UTF-8");

try {
//指定模板路径
Template template=configuration.getTemplate(templatePath,"UTF-8");
System.out.println(template.toString());
template.setEncoding("UTF-8");
//静态页面路径
String htmlpath=context.getRealPath(targetHtmlPath);
System.out.println(htmlpath+"[htmlpath]");
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 (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}

}




package web.servlet;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import freemark.ToHtml;


public class Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, Object> map=new HashMap<String,Object>();
map.put("name", "test");
ToHtml.toHtml(getServletContext(), map, "/ftl/ck.ftl", "/html/123.html");
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值