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");
}
}