freemarker用法

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值