【问题标题】:Retrieve data from handsontable to Struts2 Action via JSON not working通过 JSON 将数据从 handsontable 检索到 Struts2 Action 不起作用
【发布时间】:2013-05-16 13:31:35
【问题描述】:

我正在使用 struts2-json 插件生成 JSON 数据和 Ajax 以使用来自该 JSON (according to the source) 的数据填充表 (handsontable)。

现在,我需要通过 JSON 使用 Ajax 将数据从表中检索到 Struts2 Action。 首先,我使用 JSON 从 Struts2 Action 传递到 Handsontable 的数据实现了填充表,这非常简单并且有效。但是为什么保存不起作用,正如您在下面的附加代码中看到的那样?

正如我在萤火虫中看到的那样,发送 POST 并在调试中在我的 JSONSaveAction 操作中检索请求,但字段数据未填充 JSON 数据,为什么?数据不应该被struts2-json插件自动绑定到java对象吗?我究竟做错了什么?

在handsontable 部分,函数handsontable.getData() 负责从表中获取整个数据。所以我像这样使用它但没有成功:

$.ajax({
        url: "../json/saveJSONDataAction.action",
        data: {data: handsontable.getData()}, //returns all cells' data
        dataType: 'json',
        type: 'POST',
        success: function (res) {
            if (res.result === 'ok') {
                $console.text('Data saved');
            }
            else {
                $console.text('Save error');
            }
        }
    });

handsontable.getData() 函数确实检索了我检查的所有数据,但在我的 JSONSaveAction 操作中,数据未绑定到 java 对象 List<Report> data。你知道为什么吗?

这是 POST 请求后我的表格和萤火虫信息的屏幕截图:

将 JSON 发送到 handsontable 的操作(工作正常):

@ParentPackage("json-default")
@Action(value="getJSONDataAction")
@Result(name="success", type="json")
public class JSONDataAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private List<Report> data = new ArrayList<Report>();

    public JSONDataAction(){
        data.add(new Report(1, "Chris", true, "2008-01-01", "orange"));
        data.add(new Report(2, "Kate", false, "2013-03-03", "blue"));
        data.add(new Report(3, "Blade", true, "2013-05-03", "black"));
        data.add(new Report(4, "Zack", false, "2013-01-01", "yellow"));
    }

    public String execute() {
        return SUCCESS;
    }

    public List<Report> getData() {
        return data;
    }

    public void setData(List<Report> data) {
        this.data = data;
    }
}

发送到自动生成的填充表的JSON:

{"data":[
    {"active":true,"color":"orange","date":"2008-01-01","id":1,"name":"Chris"},
    {"active":false,"color":"blue","date":"2013-03-03","id":2,"name":"Kate"},
    {"active":true,"color":"black","date":"2013-05-03","id":3,"name":"Blade"},
    {"active":false,"color":"yellow","date":"2013-01-01","id":4,"name":"Zack"}]
}

通过 JSON 从表中检索数据的操作(不起作用):

此处List&lt;Report&gt; data 字段始终为空,未填充来自 JSON 的数据:(

@ParentPackage("json-default")
@Action(value="saveJSONDataAction")
@Result(name="success", type="json")
public class JSONSaveAction extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private List<Report> data;

    public JSONSaveAction(){
    }

    public String execute() {
        try {
            JSONObject jsonData = (JSONObject) JSONSerializer.toJSON(data);
            String name = jsonData.getString("name");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    public List<Report> getData() {
        return data;
    }

    public void setData(List<Report> data) {
        this.data = data;
    }
}

报告类:

public class Report {
    private int id;
    private String name;
    private boolean active;
    private String date;
    private String color;

    //getters and setters
}

通过 JSON 在表中加载和保存数据:

<div id="spreadsheet">
    <p>
        <button type="button" name="load">Load</button>
        <button type="button" name="save">Save</button>
    </p>
</div>
<div id="console" class="console"></div>

<script>
    var $container = $("#spreadsheet");
    var $console = $("#console");
    var $parent = $container.parent();
    $container.handsontable({
        startRows: 4,
        startCols: 20,
        rowHeaders: true,
        colHeaders: true,
        contextMenu: true,
        columns: [
            {data: "id", type: 'text'},
            {data: "name", type: 'text'},
            {data: "active", type: 'checkbox'},
            {data: "date", type: 'date'},
            {data: "color",
                type: 'autocomplete',
                source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"]
            }
        ]
    });
    var handsontable = $container.data('handsontable');

    $parent.find('button[name=load]').click(function () {
        $.ajax({
            url: "../json/getJSONDataAction.action",
            dataType: 'json',
            type: 'GET',
            success: function (res) {
                handsontable.loadData(res.data);
                $console.text('Data loaded');
            }
        });
    });

    $parent.find('button[name=save]').click(function () {     
        $.ajax({
            url: "../json/saveJSONDataAction.action",
            data: {data: handsontable.getData()}, //returns all cells' data
            dataType: 'json',
            type: 'POST',
            success: function (res) {
                if (res.result === 'ok') {
                    $console.text('Data saved');
                }
                else {
                    $console.text('Save error');
                }
            },
            error: function () {
                $console.text('Save error.');
            }
        });
    });
</script>

请帮助我如何正确地从表中检索数据到 java 对象,因为它真的阻止了我。我不知道我做错了什么......

非常感谢您的任何意见!

【问题讨论】:

    标签: jquery ajax struts2 handsontable struts2-json-plugin


    【解决方案1】:

    我已经解决了。

    1:在struts.xml中添加:

    <interceptor-ref name="json">
        <param name="enableSMD">true</param>
    </interceptor-ref>
    

    2:在Ajax请求中添加:

    contentType: 'application/json'
    

    3:更改由handontable自动格式化的JSON格式。在 JSON 中有一些字符,例如:%5B %5D %7B %7D %22 而不是:[ ] { } "

    我已经用自己的 fixedEncodeURI() 函数替换了它们:

    var data = '{"data":' + fixedEncodeURI(JSON.stringify(handsontable.getData())) + '}';
    $.ajax({
        url: "../json/saveJSONDataAction.action",
        data: data, //returns all cells' data
        dataType: 'json',
        contentType: 'application/json',
        type: 'POST',
        success: function (res) {
        }
      });
    
    function fixedEncodeURI (str) {
        return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']').replace(/%7B/g, '{').replace(/%7D/g, '}').replace(/%22/g, '"');
    }
    

    【讨论】:

    • 嗨,我也遇到了同样的问题,我按照你说的做,但是在Action 类中,收到的data 实际上是List&lt;HashMap&gt; 类型,而不是List&lt;Report&gt; 类型。您是否为您的 Report 类型定义了 converter
    • 不,我不需要实现任何转换器。 struts2-json-plugin 自动完成。您需要做的就是构建可以由 struts 处理的正确 json,然后在 Action 中自动绑定到您的属性。此外,我通过设置“includeProperties”和“ignoreHierarchy”在我的 Action 中声明了哪些字段应仅用于序列化和反序列化。
    【解决方案2】:

    我没有仔细查看您的代码,但乍一看,当您在Action 中使用new ArrayList&lt;Report&gt;() 创建一个新集合时,您似乎正在删除data 集合。不用管声明private List&lt;Report&gt; data;

    【讨论】:

    • 我已经修复了它,但它没有帮助。
    猜你喜欢
    • 2014-12-17
    • 1970-01-01
    • 2013-11-03
    • 2014-04-22
    • 2014-02-01
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多