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
Since I am using name,value I must get it by using name. Below is the working code
To send data with the POST request you should use
data
property like thisTo get the data in the action bean you need to use public setter
To return data back to the
success
callback function use public getterTo return JSON from the action use result type
json
.Note, if you add
json
interceptor to the action config you can use JSON data in the request. UsingContent-Type: "application/json"
with the request will trigger Struts2 to parse the request and deserialize it to the action bean automatically.