天天看點

碼農小汪-struts2學習9-json資料的傳回

為啥子,我要說這個問題呢?實在是太流行的傳遞資料的方式,非常特别的就是作為手機客服端的時候,我們和伺服器進行交流,這個是難免的,必須實行的手段,json作為當時,xml傳遞資料的代替者,還是非常的友善的。使用倒是很簡單。

第一種方式啊,還是非常的簡單,類似我們的servlet中的一樣的

PrintWriter out = response.getWriter();
        //将要被傳回到用戶端的對象
        User user=new User();
        user.setId("123");
        user.setName("JSONServlet");
        user.setPassword("JSON");
        user.setSay("Hello , i am a servlet !");
        JSONObject json=new JSONObject();
        json.accumulate("success", true);
        json.accumulate("user", user);
        out.println(json.toString());
        out.flush();
        out.close();
如上就是直接在servlet中執行的資料是一樣的效果啊,在exe...這個方法中,不需要有傳回值,直接把方法的傳回值該為void 在xml配置檔案中沒得result這個屬性,簡單暴力的處理
package name="loginAction" namespace="/user" extends="struts-default">
        <action name="login" class="userAction" method="userLogin"></action>
        <action name="checkUser" class="userAction" method="checkUser"></action>
        <action name="register" class="userAction" method="register"></action>
    </package>
和以前沒得什麼變化的,都是簡單的改變,沒得傳回值啦,這些都在一個方法體重的,因為是寫的android的驗證,是以沒得result這個屬性,也沒有利用structs2中的json的處理方式,其實都可以的,隻要可以得到解決的方案都是可以的。      

利用屬性設定來處理,

這個時候jsp頁面可以的,如果在Android端的話或者通過ajax異步請求的也是不能得到結果的,這樣的方式不可以的,我們不可以共享屬性這種事情啊

User user = new User();
        user.setId("123");
        user.setName("Struts2");
        user.setPassword("123");
        user.setSay("Hello world !");
        JSONObject jsonObject=new JSONObject();
        jsonObject.accumulate("user", user);
        //這裡在request對象中放了一個data,是以struts的result配置中不能有type="redirect" 
        ServletActionContext.getRequest().setAttribute("data", jsonObject.toString());
        return SUCCESS;

jsp頁面隻要簡單的給個值就行了
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 ${data }      

在Action中以Struts2的方式輸出JSON資料

dataMap是Action中的一個屬性值

dataMap.clear();
        User user = new User();
        user.setId("123");
        user.setName("JSONActionStruts2");
        user.setPassword("123");
        user.setSay("Hello world !");
        dataMap.put("user", user);
        // 放入一個是否操作成功的辨別
        dataMap.put("success", true);
        // 傳回結果
        return SUCCESS;      

在xml配置中怎麼處理呢?

package name="json" extends="json-default" namespace="/test">
        <action name="testByAction"class="json.demo.action.UserAction" >
            <result type="json">
<!-- 這裡指定将被Struts2序列化的屬性,該屬性在action中必須有對應的getter方法 -->
                <param name="root">dataMap</param>
            </result>
        </action>
</package>      

我在文檔中看到的,Json傳回的屬性中不止root這個屬性可以設定的還有些其他的,我就講一些可以用的吧,可能用的比較少,我覺得第一種比較實在點啊,不用配置。

  • 正規表達式的逗号分隔清單可以傳遞到JSON結果和攔截器,屬性比對這些正規表達式将被忽略在序列化過程:
<!-- Result fragment -->
<result type="json">
  <param name="excludeProperties">//不包括那些屬性
    login.password,
    studentList.*\.sin
  </param>
</result>      
  • Use the “root” attribute(OGNL expression) to specify the root object to be serialized.對跟對象進行序列化,隻對她處理澀
<result type="json">
  <param name="root">和我們上面的一樣
    person.job
  </param>
</result>      

預設屬性上定義基類的對象不會被序列化的“根”,序列化屬性在所有基類(對象)設定“ignoreHierarchy”假的JSON結果:

By default properties defined on base classes of the “root” object won’t be serialized, to serialize properties in all base classes (up to Object) set “ignoreHierarchy” to false in the JSON result:

父親的屬性要不要包括進來,預設不包括的

<result type="json">
  <param name="ignoreHierarchy">false</param>
</result>      

防止浏覽器緩存響應

<result type="json">
  <param name="noCache">true</param>
</result>      

不包括屬性與零值

<result type="json">
  <param name="excludeNullProperties">true</param>
</result>      

狀态和錯誤代碼

<result type="json">
  <param name="statusCode">304</param>
</result>      

内容類型

<result type="json">
  <param name="contentType">text/html</param>
</result>      

編碼

<result type="json">
  <param name="encoding">UTF-8</param>
</result>      

例子

import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class JSONExample {
    private String field1 = "str";
    private int[] ints = {10, 20};
    private Map map = new HashMap();
    private String customName = "custom";

    //'transient' fields are not serialized
    private transient String field2;

    //fields without getter method are not serialized
    private String field3;

    public String execute() {
        map.put("John", "Galt");
        return Action.SUCCESS;
    }

    public String getField1() {
        return field1;
    }

    public void setField1(String field1) {
        this.field1 = field1;
    }

    public int[] getInts() {
        return ints;
    }

    public void setInts(int[] ints) {
        this.ints = ints;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    @JSON(name="newName")
    public String getCustomName() {
        return this.customName;
    }
}      
import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Result;

@Result(type = "json")
public class JSONExample extends ActionSupport {
// action code
把上面的放進來就行了
}      

xml中的配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

  <package name="example"  extends="json-default">
     <action name="JSONExample" class="example.JSONExample">
        <result type="json"/>
     </action>
  </package>

</struts>      

輸出的結果

{  
   "field1" : "str", 
   "ints": [10, 20],
   "map": {
       "John":"Galt"
   },
   "newName": "custom"
}      

doc中的也是看的查不多了…自己去看看吧,碼農加油!