Passing serialize array to struts2 action

2020-04-12 09:49发布

问题:

I am planning to post entire form data in JSON format to Struts2 Action. Below are my code snippets. Correct me where I am going wrong or Help me so that I can get all values in the Action file correctly. All of my SOPs in Action file is displayed as null

var MyForm = $("#companyform").serializeArray();
   var data = JSON.stringify(MyForm);


   $.ajax({
       type: 'POST',
       url:'createcompany.action?jsonRequestdata='+data,
       dataType: 'json',
       success: function(data){
             console.log(stringify(data));
        }});

My form data is turned into [{"name":"tan","value":"rrr"},{"name":"pan","value":"adf"},{"name":"tod","value":"1"}]

Struts2 Action File:

String jsonRequestdata;
public String execute() throws Exception {
    JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata);
    JSONObject json = (JSONObject) jsonArr.get(0);


    System.out.println("TAN=" + json.get("tan"));
    System.out.println("PAN=" + json.get("pan"));
    System.out.println("TOD=" + json.get("tod"));
    return "success";
}

Present OUTPUT

TAN=null
PAN=null
TOD=null

回答1:

To send data with the POST request you should use data property like this

$.ajax({
   type: 'POST',
   url:'createcompany.action'
   data: 'jsonRequestdata='+data
   dataType: 'json',
   success: function(data){
      console.log(JSON.stringify(data.jsonRequestdata));
   }
});

To get the data in the action bean you need to use public setter

public void setJsonRequestdata(String data){ this.jsonRequestdata = data; }

To return data back to the success callback function use public getter

public String getJsonRequestdata(){ return this.jsonRequestdata; } 

To return JSON from the action use result type json.

<result type="json"><param name="includeProperties">jsonRequestdata</param></result>

Note, if you add json interceptor to the action config you can use JSON data in the request. Using Content-Type: "application/json" with the request will trigger Struts2 to parse the request and deserialize it to the action bean automatically.



回答2:

Since I am using name,value I must get it by using name. Below is the working code

JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata);

    for(int i=0;i<jsonArr.size();i++){
            JSONObject json=(JSONObject) jsonArr.get(i);   
            System.out.println("name=" + json.get("name"));
            System.out.println("value=" + json.get("value"));
    }