Struts2 与 freemarker 生成Json、XML 的模板

必须加入的包有jsonplugin-0.30.jar,xsttream-1.3.jar,freemarker-2.3.8.jar

Xml代码

  1. ///struts.xml 
  2. <struts>
  3. <include file="struts-default.xml"/>
  4. <package name="json" extends="json-default">
  5. <action name="extjs" class="book.action.ExtjsAction">
  6. <result type="json"/><!-- 这里生成Json -->
  7. </action>
  8. <action name="extjsXml" class="book.action.ExtjsAction">
  9. <result type="freemarker">
  10. <param name="location">template/gridXml.ftl</param>
  11. <param name="contentType">application/xml</param>
  12. </result>
  13. </action>
  14. </package>
  15. </struts>
///struts.xml

<struts>

    <include file="struts-default.xml"/>

    <package name="json" extends="json-default">

        <action name="extjs" class="book.action.ExtjsAction">

            <result type="json"/><!-- 这里生成Json -->

        </action>

        <action name="extjsXml" class="book.action.ExtjsAction">

            <result type="freemarker">

	            <param name="location">template/gridXml.ftl</param>

	            <param name="contentType">application/xml</param>

            </result>

        </action>

    </package>

</struts>

模板如下,

Xml代码

  1. //src/template/gridXml.ftl 
  2. <?xml version="1.0" encoding="utf-8"?>
  3. <list>
  4. <Total>
  5. <results>${results}</results>
  6. </Total>
  7. <#list items as item>
  8. <#assign recordName=item.class.name.replaceAll(".*\\.","")>
  9. <${recordName}>
  10. <#assign methods=item.class.declaredMethods>
  11. <#list methods as method>
  12. <#assign isGetMethod=method.name.startsWith("get")>
  13. <#if isGetMethod = true>
  14. <#assign methodmethodName=method.name.replaceAll("get","").toLowerCase()>
  15. <${methodName}>
  16.                 ${method.invoke(item,null)} 
  17. </${methodName}>
  18. </#if>
  19. </#list>
  20. </${recordName}>
  21. </#list>
  22. </list>

你可能感兴趣的:(freemarker)