How to send Json to Struts2?

There is a Json object, and I don’t know how to get it in struts2, it has two arrays in it, how to pass it to ArrayList in java?

enter image description here

var params = {
        'goodsIdList':goodsIdList,
        'goodsCountList':goodsCountList
    }
    console.log(params);
    $.ajax({
        type: 'post',
        url: "checkGoodsIsEnough",
        data: params,
        dataType:"json",
        async: true,
        success: alert("success"),
        error: function (jqXHR) {
            alert(jqXHR.status);
        }

    })
+1
source share
2 answers

I will assume that you have already added this configuration to your struts.xml to provide support for the JSON format:

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

If so, be sure to convert the javascript object to JSON string format using:

var JsonParams = JSON.stringify(params);

And then try to make the mail call like this:

$.ajax({
    type: 'post',
    url: "checkGoodsIsEnough",
    data: JsonParams,
    dataType:"json",
    async: true,
    success: alert("success"),
    error: function (jqXHR) {
        alert(jqXHR.status);
    }

});

Hope this help!

+2
source

You need struts2-json-plugin .

It fulfills two main goals:

# 1. Java JSON json ( Action JSP );

# 2. Javascript JSON json ( JSP Action).

, ( , ) , json, :

<package name="myPackage" extends="json-default">
...
    <action name="myAction" class="foo.bar.MyAction">

        <interceptor-ref name="json"         /> <!-- #2 is here -->
        <interceptor-ref name="defaultStack" />

        <result name="success" type="json"> <!-- #1 is here -->
            <param name="root">myJavaObjectThatWillBecomeJson</param>
        </result>
        <result name="error">error.jsp</result>
    </action>
    ...

, , ( ) , , , .

json Interceptor :

  • "content-type" "application/json"
  • JSON , . json.org .
  • setter , .
  • : Primitives (int, long... String), Date, List, Map, Primitive Arrays, Other class ( ) Array of Other class.
  • JSON, , , Map ( ), Long, List.
0

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


All Articles