fleshlight使用方法

2016-12-02

FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据。下面是小编为您带来的freemarker 调用java方法,希望对大家有所帮助。

freemarker 调用java方法:

The TemplateHashModel returned from BeansWrapper.getStaticModels() can be used to create hash models for accessing static methods and fields of an arbitrary class.

BeansWrapper wrapper = BeansWrapper.getDefaultInstance();

TemplateHashModel staticModels = wrapper.getStaticModels();

TemplateHashModel fileStatics =

(TemplateHashModel) staticModels.get("java.io.File");

And you will get a template hash model that exposes all static methods and static fields (both final and non-final) of the java.lang.System class as hash keys. Suppose that you put the previous model in your root model:

root.put("File", fileStatics);

From now on, you can use ${File.SEPARATOR} to insert the file separator character into your template, or you can even list all roots of your file system by:

<#list File.listRoots() as fileSystemRoot>...

Of course, you must be aware of the potential security issues this model brings.

You can even give the template authors complete freedom over which classes' static methods they use by placing the static models hash into your template root model with

root.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());

This object exposes just about any class' static methods if it's used as a hash with class name as the key. You can then use expression like${statics["java.lang.System"].currentTimeMillis()} in your template. Note, however that this has even more security implications, as someone could even invoke System.exit() using this model if the method exposure level is weakened to EXPOSE_ALL.

Note that in above examples, we always use the default BeansWrapper instance. This is a convenient static wrapper instance that you can use in most cases. You are also free to create your own BeansWrapper instances and use them instead especially when you want to modify some of its characteristics (like model caching, security level, or the null model representation).

freemarker相关知识点拓展:

模板并没有包含程序逻辑来查找当前的访问者是谁,或者去查询数据库获取最新的产品。 显示的数据是在 FreeMarker之外准备的,通常是一些“真正的”编程语言(比如Java)所编写的代码。模板作者无需知道这些值是如何计算出的。事实上,这些值的计算方式可以完全被修改,而模板可以保持不变,而且页面的样式也可以完全被修改而无需改动模板。当模板作者(设计师)和程序员不是同一人时,显示逻辑和业务逻辑相分离的做法是非常有用的,即便模板作者和程序员是一个人,这么来做也会帮助管理应用程序的复杂性。保证模板专注于显示问题(视觉设计,布局和格式化)是高效使用模板引擎的关键[8] 。

通用

能够生成各种文本:HTML、XML、RTF、Java源代码等等。

易于嵌入到产品中:轻量级;不需要Servlet环境。

插件式模板载入器:可以从任何源载入模板,如本地文件、数据库等等。

可以按所需生成文本:保存到本地文件;作为Email发送;从Web应用程序发送它返回给Web浏览器。

强大的模板语言

所有常用的指令:include、if/elseif/else、循环结构。

在模板中创建和改变变量。

几乎在任何地方都可以使用复杂表达式来指定值。

命名的宏,可以具有位置参数和嵌套内容。

名字空间有助于建立和维护可重用的宏库,或者将一个大工程分成模块,而不必担心名字冲突。

输出转换块:在嵌套模板片段生成输出时,转换HTML转义、压缩、语法高亮等等;可以定义自己的转换。

更多相关阅读

最新发布的文章