简体   繁体   English

JSON Jquery到Struts2的动作

[英]JSON Jquery to Struts2 action

I want to send my JSON object from Javscript to Struts2 Action. 我想将JSON对象从Javscript发送到Struts2 Action。

Sample JSON Object 示例JSON对象

  {
        "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 我的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 Struts.xml配置

<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. 我的问题是如何在Action Class中接收JSON对象。

NOTE: POST OF JSON object is successful.. I just don't know how to receive it via Action Class.. PLEASE HELP Thank you 注意:POST OF JSON对象成功..我只是不知道如何通过Action Class接收它..请帮助谢谢

  1. There is a typo in your struts.xml entry struts.xml条目中有一个拼写错误
  2. Have you defined tiles result and interceptor in struts.xml . 你有没有在struts.xml定义tile结果和拦截器。 Please see this link 请看这个链接
  3. The json you are sending to the server, doesn't contain any data key. 您要发送到服务器的json不包含任何data密钥。 So it will be always null. 所以它总是空的。 Since json is denoted as objects. 因为json被表示为对象。 You need to convert JSON into Java objects in this way. 您需要以这种方式将JSON转换为Java对象。

Approach 1. 方法1。

Create setters for lists,maps,number1,numberarray1,string1 and so on. lists,maps,number1,numberarray1,string1等创建setter。 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. 方法2.在你的javascript中定义一个新对象。

 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. 在你的动作类中,为此创建getter和setter。

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

This will give you whole json object as a Map. 这将为您提供整个json对象作为Map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM