我试图从js获取JSON数据并在动作类中接收null

时间:2015-10-27 08:35:44

标签: javascript json ajax struts2 struts2-json-plugin

我从客户端获取JSON。我想通过ajax发送它。但是,我在我的动作类中得到了null。

我的JSON字符串

{"data":[{"id":"","col":1,"row":1,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":2,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":3,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":4,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":6,"size_x":1,"size_y":1},
         {"id":"","col":1,"row":5,"size_x":1,"size_y":1}
        ]
}

AJAX

var seats = {"data" : positions};

    var seatPosition = JSON.stringify(seats);

    console.log(seatPosition);  

    $.ajax({
        url: 'retrieve-seat',
        data: seatPosition,
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        async: true,
        success: function (data) {
        alert("success");

struts.xml中

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

<constant name="struts.devMode" value="true" />
<constant name="struts.action.extension" value="," />
<constant name="struts.enable.SlashesInActionNames" value="true" />
<constant name="struts.custom.i18n.resources" value="global" />

<package name="default" namespace="/"
    extends="json-default,struts-default">

    <action name="retrieve-seat" class="com.pointwest.apex.actions.ReadPositionAction">
        <result name="SUCCESS" type="json"/>
    </action>

</package>

</struts>

Action.class

public class ReadPositionAction extends ActionSupport {

private List<Seat> data;


public List<Seat> getData() {
     System.out.println("Getter Call");
    return data;
}

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

@Override
public String execute() {
    System.out.println("action");
    try {
        System.out.println(data);


        System.out.println("Execute Method");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "SUCCESS";
}

}

控制台日志似乎显示JSON的正确格式。有人请帮助我谢谢!

1 个答案:

答案 0 :(得分:0)

如果您需要生成 JSON(操作 - &gt; JSP), json结果就足够了。

如果您需要消费 JSON(JSP - &gt; Action),您需要将 Json Interceptor 添加到您的堆栈。

来自the documentation

  

接受JSON

     

您的操作可以接受传入的JSON,如果它们在包中   使用json拦截器或通过添加对它的引用如下:

@InterceptorRef(value="json")

另请注意,json-default包内部扩展了struts-default,因此无需扩展它们。

应该是:

<package name="default" namespace="/" extends="json-default">

    <interceptor-stack name="jsonFromJspStack">
        <interceptor-ref name="defaultStack"/>
        <interceptor-ref name="json" />
    </interceptor-stack>


    <action name="retrieve-seat" class="com.pointwest.apex.actions.ReadPositionAction">
        <interceptor-ref name="jsonFromJspStack"/>
        <result name="SUCCESS" type="json"/>
    </action>

</package>