星空网 > 软件开发 > Java

Freemarker中Configuration的setClassForTemplateLoading方法参数问题

今天使用freemarker中Configuration的setClassForTemplateLoading方法遇到了加载模板目录的一个小问题。

由于网上的其他论坛,博客写的有点乱,故记录一下。

 

Freemarker是一个模板框架,主要是为了加快染速度而产生的。它与web容器无关,只要是关于模板生成一些代码的都可以使用它完成。

比如

 

本文主要讲的是Freemarker的加载模板目录问题,它的语法就不描述了。具体的语法可在官网下载参考手册参考即可。

加载模板目录方法

Freemarker提供了3种加载模板目录的方法。 它使用Configuration类加载模板

3种方法分别是:

public void setClassForTemplateLoading(Class clazz, String pathPrefix);

public void setDirectoryForTemplateLoading(File dir) throws IOException;

public void setServletContextForTemplateLoading(Object servletContext, String path);

看名字也就知道了,分别基于类路径、文件系统以及Servlet Context。

 

第二,三种没啥好说的。

第二种基于文件系统。 比如加载/home/user/template下的模板文件。

Configuration cfg = new Configuration();cfg.setDirectoryForTemplateLoading(new File("/home/user/template"));cfg.getTemplate("Base.ftl");

这样就获得了/home/user/template/Base.ftl这个模板文件。

 

第三种基于web project。 第二个参数是基于WebRoot下的。

比如: setServletContextForTemplateLoading(context, "/ftl") 就是 /WebRoot/ftl目录。

 

第一种基于类路径的方法有点小坑,其实看下源码代码就知道了。

比如 :

Configuration cfg = new Configuration();cfg.setClassForTemplateLoading(FreemarkerUtil.class, "/template");cfg.getTemplate("Base.ftl");

其中FreemarkerUtil所在的包路径是:  org.foo.util

那么获得是模板文件就是  ${projectPath}/org/foo/util/template 。

 

这里注意一下第二个参数需要以 "/" 开头。

 

其实我们看下源码就知道了:

 Freemarker中Configuration的setClassForTemplateLoading方法参数问题

 Freemarker中Configuration的setClassForTemplateLoading方法参数问题

Freemarker中Configuration的setClassForTemplateLoading方法参数问题

Freemarker中Configuration的setClassForTemplateLoading方法参数问题

可以看到,prefix如果最后1个字符不是 "/" 会默认加上。 但是第一个不是 "/" 字符 并不会加上。

 

最终的具体生成代码是通过FMParser这个类生成的。  FMParser是使用JavaCC写的,由于时间有限,就没有具体研究了。

参考资料

http://my.oschina.net/flashsword/blog/160747




原标题:Freemarker中Configuration的setClassForTemplateLoading方法参数问题

关键词:FreeMarker

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

又有老板被代运营骗了!:https://www.ikjzd.com/articles/132152
2020 Wish年度卖家云峰会,人、货、运的全面升级!:https://www.ikjzd.com/articles/132153
亚马逊换标具体步骤,把握换标的几个关键点:https://www.ikjzd.com/articles/13216
亚马逊9.9美元包邮能在半年赚300万?:https://www.ikjzd.com/articles/132177
海运价格飞涨3倍冲上热搜 高价可能持续到2021年:https://www.ikjzd.com/articles/132178
亚马逊prime day收官,黑五网一还有哪些品类能爆?:https://www.ikjzd.com/articles/132180
美众议院对TikTok“动手”,下一步该怎么在TikTok上营销?:https://www.kjdsnews.com/a/1836587.html
速卖通在韩国争议不断,投诉量激增两倍:https://www.kjdsnews.com/a/1836588.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流