struts2的json plugin可以實現(xiàn)struts2和json的完美結(jié)合,由于本篇主要是介紹整合過程中遇到的問題,所以編程實現(xiàn)的方法這里就不重復了,具體可以參看struts2的官方文檔:http://struts.apache.org/2.2.1.1/docs/json-plugin.html。
我在struts.xml中有如下action定義:
<action name="product_group" class="customers.products" method="getGroups">
<result type="json">
<param name="root">groupList</param>
</result>
</action>在上面的定義中,action的result的type為json,json plugin就可將action中定義為groupList的field自動轉(zhuǎn)換為json格式數(shù)據(jù),并返回給前端UI。
但在deploy后,啟動tomcat時卻報了There is no result type defined for type 'json' mapped with name 'success'. Did you mean 'json'?的錯誤,因為struts2找不到j(luò)son這個result type的定義。解決方法有下面兩種:
1.將當前package的extends屬性改為"json-default",即讓當前package從josn-default繼承而不是struts-default繼承;
2.但如果當前package確實無法繼承"json-default"的話,還可以在當前package中定義result-type,將json給加進去,如下:
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"/>
</result-types>兩種方法的原理:
json這個result type是在json-default (struts2-json-plugin-2.1.8.1.jar\struts-plugin.xml)里面定義的,內(nèi)容如下(省去了xml和doctype標簽):
<struts>
<package name="json-default" extends="struts-default">
<result-types>
<result-type name="json" class="org.apache.struts2.json.JSONResult"/>
</result-types>
<interceptors>
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
</interceptors>
</package>
</struts>可見,name為"json"的result type是在json-default中定義的,所以,從json-default繼承就可以使用json這個result。另外json-default還定義了一個name為"json"的interceptor。
另外,依json-default的定義來看,
然后在你配置的攔截器聲明中加上
<interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
也就是json攔截器的聲明,接下來再在你的default-stack-ref(或者其他攔截器引用的地方)引用這個名字為json的攔截器就可以了 搞定 收工~