1. 程式人生 > >struts2.0.11整合jsonplugin0.32的方法。

struts2.0.11整合jsonplugin0.32的方法。

json 用在web開發中伺服器端與客戶端互動資料非常重要,特別是在流程的Ajax應用中顯得重要,這裡談談在struts2中整合json外掛的方法,解放在web開發中不停拼json String的困擾。

步驟1:下載Strut2的最小集合包和json的外掛包。

xwork-2.0.4.jar

struts2-core-2.0.11.1.jar

ognl-2.6.11.jar

freemarker-2.3.8.jar

commons-logging-1.0.4.jar

jsonplugin-0.32.jar

注意struts2.1以上版本要下載jsonplugin-0.34.jar否則會有問題。

將以上包匯入工程中,細節就不說了。

步驟2:編寫輸出json的action類,這裡舉例JsonDemo類。

我的演示類如下:

 

說明一下,使用json外掛的好處就是不在去寫將Object轉換成json的程式碼了,框架制動為你轉換,前提是你的定義的類是個標準的javabean,原始型別除外。具體規範我這裡黏貼上官方的英文說明:

The JSON plugin provides a "json" result type that serializes actions into JSON. The serialization process is recursive, meaning that the whole object graph, starting on the action class (base class not included) will be serialized (root object can be customized using the "root" attribute). If the interceptor is used, the action will be populated from the JSON content in the request, these are the rules of the interceptor:

  1. The "content-type" must be "application/json"
  2. The JSON content must be well formed, see json.org for grammar.
  3. Action must have a public "setter" method for fields that must be populated.
  4. Supported types for population are: Primitives (int,long...String), Date, List, Map, Primitive Arrays, Other class (more on this later), and Array of Other class.
  5. Any object in JSON, that is to be populated inside a list, or a map, will be of type Map (mapping from properties to values), any whole number will be of type Long, any decimal number will be of type Double, and any array of type List.

步驟3:在struts.xml中配置JsonDemo這個Action。

 

這裡注意兩個問題:

1.extends必須繼承於son-default。

2、返回的型別必須為<result type="json"/>

步驟4:寫測試

這裡推薦使用一個客戶端工具restclient-ui-2.3-jar-with-dependencies.jar可以再一下地址取下載

json格式化工具推薦用JSON Viewer

結果為:

{

    "isture": false,

    "list": [

        "data1",

        "data2"

    ],

    "map": {

        "key2": "keydata3",

        "key1": "keydata1"

    },

    "name": "張三",

    "num": 100,

    "operation": {

        "operationName": "使用者登入",

        "operationType": "2",

        "operationURL": "/agent/login.action"

    }

}