动态生成加载ftl模板

ftl文件。

jsp:

  <% String topMenu = FreeMakerUtil.transformData("topMenu.ftl", rootMap); %>

  <div class="topmenu">
   <%=topMenu%>
  </div>

public class FreeMakerUtil {
 private static Logger log = LoggerFactory.getLogger(FreeMakerUtil.class);
 private static final String templates = "templates";
 private static Configuration cfg = null;
 public static final int DEFAULT_WRAPPER = 1;
 public static final int BEANS_WRAPPER = 2;
 public static final int SIMPLE_WRAPPER = 3;
 
 public static String transformData(String templateName,Object rootMap,int wapperType){
  StringWriter writer = new StringWriter();
  try {
   switch (wapperType) {
   case BEANS_WRAPPER:
    cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
    break;
   case SIMPLE_WRAPPER:
    cfg.setObjectWrapper(ObjectWrapper.SIMPLE_WRAPPER);
    break;
   default:
    cfg.setObjectWrapper(ObjectWrapper.DEFAULT_WRAPPER);
    break;
   }
   Template template = cfg.getTemplate(templateName);
   template.process(rootMap, writer);
  } catch (Exception e) {
   log.error("transformData",e);
  }
  return writer.toString();
 }
 public static String transformData(String templateName,Object rootMap){
  return transformData(templateName,rootMap,DEFAULT_WRAPPER);
 }
 public static void initConfiguration(){
  URL url = FreeMakerUtil.class.getClassLoader().getResource(templates);
  initConfiguration(url.getPath());
 }
 public static void initConfiguration(String templatePath){
  try {
   if(cfg==null) cfg = new Configuration();
   cfg.setDirectoryForTemplateLoading(new File(templatePath));
   cfg.setDefaultEncoding("UTF-8");
   cfg.setOutputEncoding("UTF-8");
  } catch (Exception e) {
   log.error("initConfiguration",e);
  }
 }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值