官方文档地址:

2009年的地址
http://freemarker.sourceforge.net/docs/pgui_misc_beanwrapper.html#autoid_54

 

https://freemarker.apache.org/docs/pgui_misc_beanwrapper.html#autoid_60   更新于2018-05-23

Accessing static methods

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

FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法
BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
TemplateHashModel staticModels = wrapper.getStaticModels();
TemplateHashModel fileStatics =
    (TemplateHashModel) staticModels.get("java.io.File"); 
FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法

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:

FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法
root.put("File", fileStatics); 
FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法

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:

FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法
<#list File.listRoots() as fileSystemRoot>...</#list> 
FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法

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

FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法
root.put("statics", BeansWrapper.getDefaultInstance().getStaticModels()); 
FreeMarker调用JAVA静态方法
FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法 FreeMarker调用JAVA静态方法

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).

相关文章: