How to use jQuery to send JSON data to Action Struts2 class

I have a problem sending data from jQuery to the struts2 action class. I saw a question: JSON JQuery for a Struts2 action , but I don't understand the solution very well.

Here is my problem:

The json array looks like this:

[{"id":"1","code":"111","name":"ddd"}, {"id":"2","code":"222","name":"sss"}, {"id":"3","code":"333","name":"eee"}] 

I want to send json data to struts2 action class. The jQuery code is as follows:

 var data = JSON.stringify(dataObj); $.ajax({ url: "Update", type: "post", data: data, dataType: 'json', contentType:"application/json;charset=utf-8", success : function(){ alert("You made it!"); } }); 

However, in the Chrome Development Tool, I saw data submitted to the server. But on the server side, I don't know how to get json data.

Act:

 public class Update extends ActionSupport{ private String data; public String getData(){ return data; } public void setData(String data){ this.data= data; } public String execute(){ System.out.println(data); return SUCCESS; } } 

So data is null.

I also tried using List to get JSON data. Changing the data type from String to List<Node> , it again failed. Perhaps because I do not quite understand the OGNL model that Struts2 uses.

Please help me. Thank you very much!

+6
source share
2 answers
 {"id":"1","code":"111","name":"ddd"} 

Step 1. Create a bean / pojo to accumulate / encapsulate the above fields

 class MyBean{ String id,code,name; //getters & setters } 

Step 2. Change the action code to get a list of MyBeans

 public class Update extends ActionSupport{ private List<MyBean> data; //other code, getters & setters } 

Step 3. Configure the action to de-serialize JSON data and fill in the action fields (using json-plugin)

  <action name="Update" class="Update"> <interceptor-ref name="defaultStack"/> <interceptor-ref name="json"> <param name="enableSMD">true</param> </interceptor-ref> </action> 

Step 4: Make the necessary changes to the body of the ajax request sent to match the parameters / action fields

 var data = JSON.stringify(dataObj); $.ajax({ url: "Update", type: "post", data: "data:"+data, dataType: 'json', contentType:"application/json;charset=utf-8", success : function(){ alert("You made it!"); } }); 

The above code is not verified.

+8
source

Hey. The problem is that you are directly sending an array of objects. So Struts2 does not know which method to call. Change json data as below. Then it will work.

 {"data":[{"id":"1","code":"111","name":"ddd"}, "id":"2","code":"222","name":"sss"}, {"id":"3","code":"333","name":"eee"}]} 

Then inside the setter read from the object

 public void setData(List < Report > data) { System.out.println("Setter Call Flow"); this.data = data; } 

Where Report is a java class containing id, code, name as its members with setters and getters.

+1
source

Source: https://habr.com/ru/post/956645/


All Articles