JSON jQuery to action Struts2

I want to send my JSON object from Javscript to Action Struts2.

JSON Object Example

{ "lists":["list1","list2","list3","list4","list5"], "maps": { "key4":"value4","key3":"value3","key5":"value5","key2":"value2","key1":"value1" }, "number1":123456789, "numberarray1":[1,2,3,4,5,6,7,8,9], "string1":"A", "stringarray1":["A1","B1"] } 

My jquery ajax

 $.ajax({ type: 'POST', url: 'json/JSON.action', data: JSON.stringify(data), dataType: 'json', async: false , contentType: 'application/json; charset=utf-8', success: function(){window.alert('Done');} }); 

Struts.xml Configuration

 <action name="JSON" class="com.actions.json.JsonAction" method="getJSON"> <result type="json"/> </action> 

My action class

 public class JsonAction extends ActionSupport { private String data; public String getJSON() { return ActionSupport.SUCCESS; } public String getData() { return data; } public void setData(String data) { this.data = data; } } 

My problem is how to get the JSON object in the Action class.

NOTE: The POST of the JSON object is successful. I just don’t know how to get it through the Action Class .. PLEASE HELP Thank you

+6
source share
1 answer
  • There is a typo in your struts.xml entry
  • You defined the tile result and interceptor in struts.xml . Please view this link.
  • The json that you send to the server does not contain the data key. Therefore, it will always be zero. Since json is designated as an object. So you need to convert JSON to Java objects.

Approach 1.

Create setters for lists,maps,number1,numberarray1,string1 , etc. At the top, this link defines how it is executed. Then you can access all the variables this way.

Approach 2. In javascript, define a new object.

  var sentData ={}; sentData ["sentData "] = data; // And in your ajax call , data: JSON.stringify(sentData), 

And in your action class, create getters and setters for this.

 Map<KV> sentData = new HashMap<K,V>(); 

This will give you the whole json object as a map.

+6
source

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


All Articles