最近开发一个基于组件的开发平台,其中遇到一个问题就是:要在程序运行时根据某个配置,动态地去加载Freemarker模板,经过查阅相关资料和查看Struts的FreemarkerResult源码解决了这个问题,步骤大约是:
1、新定义个类,比如叫做ExampleFreemarkerResult,并且extends基类org.apache.struts2.views.freemarker.FreemarkerResult,覆写FreemarkerResult的方法:
public void doExecute(String locationArg, ActionInvocation invocation);
注意,其中参数locationArg就是当前Struts2默认要加载的ftl模板文件的全路径,invocation是Action的调用环境,获取该环境,基本上就可以获取和Action相关的很多信息;
2、定义了这个类,那么如何让Struts2在执行完Action的逻辑后进入该Result呢?自然,我们都会想到配置到struts.xml中去,其配置如下:
<package name="struts-example" extends="struts-default">
<result-types>
<result-type name="exampleFreemarker" class="com.gsafety.cloudframework.core.environment.module.page.CloudModuleFreemarkerResult"/>
</result-types>
</package>
3、要使用该Result的Action的package都需要继承struts-example这个package,例如:
<package name="attachment" namespace="/attachment" extends="struts-example">
<action name="attachment" class="com.example.action.AttachmentAction">
<result name="main" type="exampleFreemarker">/page/fileupload.ftl</result>
</action>
</package>
好了,至此扩展就完成了,另外注意:
第一步里自定义FreemarkerResult可以实现Result的接口,而没有必要非要继承这个超类,这个大家可以查阅Struts2的FreemarkerResult源码,自然会清楚。
也可以自定 义Freemarker的Freemarker的模板加载器来,然后调用FreemarkerResult中的configuration的setTemplateLoader方法完成注册,也可以完成这样的工作,这个大家可以自己去找资料研究下。