在电商系统中经常被访问网页生成静态网页可以提高并发访问量,在全文检索系统中搜索静态网页效率也比动态网页高,所以经常被访问的网页经常被静态化。
FreemarkerUtil
package com.test.util;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import freemarker.template.Configuration;
import freemarker.template.Template;
public class FreemarkerUtil {
/**
* 根据模板和数据生成静态页面
* @param ctx Servlet上下文对象
* @param ftlPath 模板文件所在目录
* @param ftlName 模板文件名
* @param htmlPath 生成静态页面所在目录
* @param map 数据对象
*/
public static void genHtml(ServletContext ctx,String ftlPath,
String ftlName,String htmlPath,Map map)
{
try
{
//1.定义Configuration对象
Configuration conf = new Configuration(Configuration.VERSION_2_3_26);
conf.setEncoding(Locale.getDefault(), "UTF-8");
//2.设置模板加载器
conf.setServletContextForTemplateLoading(ctx, ftlPath);
//3.根据模板名称获取模板对象Template
Template tmplt = conf.getTemplate(ftlName);
//4.生成静态HTML文件
//5.从Map数据模型中获取ID
Integer id = (Integer)map.get("id");
//通过目录查询绝对地址
String path = ctx.getRealPath(htmlPath);
System.out.println("path==="+path);
String htmlFile = path + "/"+id+".html";
FileOutputStream fos = new FileOutputStream(htmlFile);
OutputStreamWriter osw = new OutputStreamWriter(fos,"UTF8");
tmplt.process(map, osw);
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
/**
* 根据文件名删除文件
* @param ctx Servlet上下文对象
* @param htmlPath 生成静态页面所在目录
* @param id 文件名
*/
public static void delHtml(ServletContext ctx,String htmlPath,Integer id)
{
try
{
String path = ctx.getRealPath(htmlPath);
String file = path + "/" + id + ".html";
File f = new File(file);
if(f.exists())
f.delete();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
String ftlPath = "ftl";
String ftlName = "good.ftl";
String htmlPath = "html";
Map map = new HashMap();
map.put("id","1");
FreemarkerUtil.genHtml(null, ftlPath, ftlName, htmlPath, map);
}
}
Controller调用代码
@RequestMapping("/save")
public String save(HttpServletRequest req,GoodInfo gi)
{
Integer id = gi.getId();
System.out.println("id==="+id);
if(id != null)
{
//修改
serv.updateGood(gi);
gi = serv.findGoodById(id);
String ftlPath = "ftl";
String ftlName = "good.ftl";
String htmlPath = "html";
Map map = new HashMap();
map.put("id", gi.getId());
map.put("name", gi.getName());
map.put("price", gi.getPrice());
map.put("dt", gi.getDt());
map.put("tname", gi.getTypeName());
FreemarkerUtil.genHtml(req.getServletContext(), ftlPath,
ftlName, htmlPath, map);
}
else
{
//新增
serv.saveGood(gi);
}
return "redirect:/list";
}