手机版
你好,游客 登录 注册
背景:
阅读新闻

Java中如何使用freemaker模版进行输出

[日期:2013-03-06] 来源:Linux社区  作者:chiweitree [字体:大 中 小]

然后写一个加载ftl文件的Java类

import java.io.StringWriter;
import java.util.Map;

import com.service.impl.MonServiceImpl;

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

/*
 * use freemarker to send email
 */
public class FreemarkUtil {
 
 private static Configuration cfg;

 private static void initialConfig() {
  cfg = new Configuration();
  cfg.setClassForTemplateLoading(MonServiceImpl.class,
    "/package的名字,用'/'隔开/");
 }
 /*
  * templateName means the ftl file name
  * param means the Object used in ftl
  */
 public static String getMail(String templateName,
   Map<String, Object> param) {
  String result = null;
  try {
   if (cfg == null) {
    initialConfig();
   }
   Template temp = cfg.getTemplate(templateName);
   StringWriter writer = new StringWriter();
   temp.process(param, writer);
   result = writer.toString();
   writer.flush();
  } catch (Exception e) {
   e.printStackTrace();
  }
  return result;
 }
}

然后在需要网ftl中输出内容的地方

paramMap.put("AM", a);  AM即FTL中的对象名,要一致


String mailContent = FreemarkUtil.getMail("FTL文件的名字.ftl",

paramMap);

mail.setContent(mailContent);

通过以上语句就可以是实现了。

linux
相关资讯       freemaker 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款