這篇我将介紹如何使用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>
轉載于:https://www.cnblogs.com/liubaozhe/p/4418741.html