一、實驗環境
1、struts2基本包

2、json-plugin
在struts2的lib下可以找到。

3、web.xml
加入struts2

<filter>
<filter-name>struts252</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts252</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
4、struts.xml
先測試一個普通的Action,確定struts正常工作了。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<!-- 開發模式(修改struts.xml不用重啟服務器) -->
<constant name="struts.devMode" value="true" />
<!-- 動態action -->
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
<package name="myPackage" namespace="/" extends="struts-default" >
<!-- 2.5 動態Action -->
<global-allowed-methods>regex:.*</global-allowed-methods>
<action name="jsonAction" class="com.xzw.json.action.JsonAction">
<result name="test1">index.jsp</result>
<result name="success">success.jsp</result>
</action>
</package>
</struts>
如果http://localhost:8080/struts2json/jsonAction和http://localhost:8080/struts2json/jsonAction!testJson1(testJson1是JsonAction內的一個方法能正確跳轉到對應jsp,那么struts2已在工作。
二、xml方式測試。
1、配置文件
strut.xml有改變,繼承的是json-default包,而json-default繼承的是struts-default。這個定義在struts2-json-plugin-2.5.2.jar的struts-plugin.xml
返回類型是json。

2、Action

3、JSP/jQuery/Ajax
JSP的一個按鈕

jQuery

4、結果
上面能正確輸出結果。字符串內容和java對象都沒有問題。需要注意,字符串與json對象之間的轉換。或者說是,符合json語法的字符串轉成JavaScript 對象(eval)。
三、注解方式。
1、導包
要使用注解,必須導入對應的包的

2、Action類
參照xml方式的設置。方法體與前面測試的一樣。

3、測試方法
由於沒有特別改變,測試只要把請求url改變就可以了。如果能和xml實驗結果一致,則成功。

運行結果與預期一致。
四、優化JSON返回的結果。
如果一個Action中有多個get方法屬性,那么上面得到實驗會返回所有。然而,一般情況只需要部分的結果就可以了。
1、為Action增加屬性

2、查看返回結果。

從這里發現,增加的get屬性已經在response了。
3、不返回某些屬性
使用參數excludeProperties
a.如,不需要myid;

b.使用正則表達式
去掉id結尾和list開頭的。如下。

含有字符“s”的都不要。

4、只返回某些屬性
使用參數includeProperties。
直接使用正則表達式作為例子。例如,只返回id結尾的。

5、注解上使用
在@Result里用上,形式如下。

