freemarker用法

来源:互联网 发布:系统优化的意义是 编辑:程序博客网 时间:2024/05/19 16:35

1、添加freemarker.jar

2、//利用freemarker 生成静态页面
 public static void crateHTML(HttpServletRequest request, Map<String, Object> data,
   String templatePath, String targetHtmlPath) {
  Configuration freemarkerCfg = new Configuration();
  //加载模版
  ServletContext context = request.getSession().getServletContext();
  freemarkerCfg.setServletContextForTemplateLoading(context, "templates"); //设置FreeMarker的模版文件位置
  freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");
  /**
   * 在第一级缓存中,组件都被强烈引用到特定的最大数目(引用次数最多
  的组件不会被Java 虚拟机抛弃,而引用次数很少的组件则相反)。当超过最大数量时,最近
  最少使用的组件将被送至二级缓存中,在那里它们被很少引用,直到达到另一个最大的数目
   */
  freemarkerCfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20,250));
  try {
   //指定模版路径
   //Template template = freemarkerCfg.getTemplate(templatePath,"UTF-8");
   Template template = freemarkerCfg.getTemplate(templatePath);
   template.setEncoding("UTF-8");
   //静态页面路径
   String htmlPath = context.getRealPath("/html") + File.separator + 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 (Exception e) {
   e.printStackTrace();
  }
//  freemarkerCfg.clearTemplateCache();   //清除缓存
 } 

 

3、在控制层方法中写:

Map<String, Object> data = new HashMap<String, Object>();
//      data.put("user","fangsidake");
      for(Newsinfo n:listNewsInfo){
       targetHtmlPath = n.getId().toString()+".html";
       data.put("newsinfo", n);
       CreateHtmlUtil.crateHTML(request, data, templatePath, targetHtmlPath);
      }

原创粉丝点击