這篇我將介紹如何使用Struts2的struts2-json-plugin.jar插件返回JSON數據。
一、其中主要步驟有:
1.將struts2-json-plugin.jar插件拷貝到項目的"/WEB-INF/lib"文件夾下;
2.編寫Action類文件;
3.在struts.xml文件中配置這個Action,這個Action所在的"<package.../>"必須繼承”json-default“, Action 的 Result 類型為 json ,即 type="json" ,而且不對應任何視圖資源。
二、示例代碼:
Action類文件:
package com.example.action; import java.util.ArrayList; import com.opensymphony.xwork2.ActionSupport; public class StrutsJsonAction extends ActionSupport { private int i=123; private String str="str"; private int[] array={1,2,3}; private ArrayList<String> list; public int getI() { return i; } public void setI(int i) { this.i = i; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } public int[] getArray() { return array; } public void setArray(int[] array) { this.array = array; } public ArrayList<String> getList() { return list; } public void setList(ArrayList<String> list) { this.list = list; } public String execute(){ list = new ArrayList<String>(); list.add("red"); list.add("green"); list.add("yellow"); return SUCCESS; } }
struts.xml文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="json-example" namespace="/" extends="json-default"> <action name="JSONExample" class="com.example.action.StrutsJsonAction"> <result name="success" type="json"/> </action> </package> </struts>
然后在瀏覽器中訪問" http://localhost:8080/Struts2_JSON/JSONExample ",顯示結果如圖:
JSON 插件會將所有可序列化 Action 屬性序列化為 JSON 數據。
三、配置常用JSON類型的Result
瀏覽器是否緩存JSON
<result type="json">
<!-- 取消瀏覽器緩存-->
<param name="noCache">true</param>
</result>
設置瀏覽器響應類型,默認為text/html
<result type="json">
<!-- 設置服務器響應類型-->
<param name="contentType">application/json</param>
</result>
排除值為 null 的屬性
<result type="json">
<!--排除值為null的屬性-->
<param name="excludeNullProperties">true</param>
</result>
只序列化指定的Action屬性
<result type="json">
<!--只序列化Action內的list屬性-->
<param name="root">list</param>
</result>
序列化包含的屬性(逗號分隔的正則表達式列表)
<result type="json">
<!--序列化list屬性-->
<param name="includeProperties">list.*</param>
</result>
<result type="json">
<!--序列化array屬性,\[和\]匹配數組的[]括號,\d匹配數字,+表示一次或多次-->
<param name="includeProperties">array\[\d+\]</param>
</result>
排除不需要被序列化的屬性(逗號分隔的正則表達式列表)
<result type="json">
<!--排除list屬性-->
<param name="excludeProperties"> list.* </param>
</result>