Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

java - JSON Jquery to Struts2 action

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

Sample JSON Object

  {
        "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 config

<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 receive the JSON Object in Action Class.

NOTE: POST OF JSON object is successful.. I just don't know how to receive it via Action Class.. PLEASE HELP Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. There is a typo in your struts.xml entry
  2. Have you defined tiles result and interceptor in struts.xml . Please see this link
  3. The json you are sending to the server, doesn't contain any data key. So it will be always null. Since json is denoted as objects. You need to convert JSON into Java objects in this way.

Approach 1.

Create setters for lists,maps,number1,numberarray1,string1 and so on. In the top of this link, is defined the way to do it. Then you can access all the variables in this way.

Approach 2. In your 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<K.V> sentData = new HashMap<K,V>();

This will give you whole json object as a Map.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...