如何使用 struts2-json-plugin 将 JSON 绑定到 Struts2 中的 Java 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16698082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:42:06  来源:igfitidea点击:

How to bind JSON to Java object in Struts2 using struts2-json-plugin

javastruts2struts2-json-plugin

提问by Roman

I want to deserialize (bind) JSON to java object. How to do it in Struts2?

我想将 JSON 反序列化(绑定)到 java 对象。如何在 Struts2 中做到这一点?

I am trying to do it with struts2-json-plugin as you can see in code below, but sent JSON from frontend is not binding to my java object. Could you help me, please how to make this code to work correctly?

我正在尝试使用 struts2-json-plugin 来完成它,如下面的代码所示,但是从前端发送的 JSON 没有绑定到我的 java 对象。你能帮我吗,请问如何使这段代码正常工作?

Please take a look at my Action class, I am not sure if I'm handling JSON correctly in this Action, or maybe I missed something?

请看一下我的 Action 类,我不确定在这个 Action 中我是否正确处理了 JSON,或者我错过了什么?

JSON which I am trying to bind:

我试图绑定的 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"}]
}

Sending JSON by Ajax:

通过 Ajax 发送 JSON:

$.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');
    }
  }
});

Receiving JSON in Struts2:

在 Struts2 中接收 JSON:

I can reach execute() method in debug, but unfortunately, the datafield is always null. What should I do to make this field filled with data from JSON?Is the JSON in correct format to bind to List<Report> data?

我可以在调试中访问 execute() 方法,但不幸的data是,该字段始终为空。我应该怎么做才能让这个字段充满来自 JSON 的数据?JSON 的绑定格式是否正确List<Report> data

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

    private List<Report> data;

    public JSONSaveAction(){
    }

    public String execute() {
        try {
            System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return NONE;
    }

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

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

Report class:

报告类:

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

    //getters and setters
}

struts.xml:

struts.xml:

As you can see here I've added <interceptor-ref name="json">with <param name="enableSMD">true</param>. Whole config below:

正如你在这里看到的,我添加<interceptor-ref name="json"><param name="enableSMD">true</param>. 整个配置如下:

<struts>
<constant name="struts.action.extension" value="action,pdf" />
<constant name="struts.i18n.reload" value="true" />
<constant name="struts.configuration.xml.reload" value="true" />
<constant name="struts.custom.i18n.resources" value="i18n/ap,application" />
<constant name="struts.date.format" value="yyyy-MM-dd" />
<constant name="struts.serve.static" value="true" />
<constant name="struts.serve.static.browserCache" value="false" />

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

    <result-types>
       <result-type name="rethrowException" class="com.myhome.commons.util.ExceptionRethrowResult" />
       <result-type name="poi-excel" class="com.myhome.commons.util.PoiExcelResult"/>
    </result-types>

    <interceptors>
        <interceptor name="businessException" class="com.myhome.commons.exception.BusinessExceptionInterceptor"></interceptor>
        <interceptor-stack name="defaultStack">
            <interceptor-ref name="exception" />
            <interceptor-ref name="alias" />
            <interceptor-ref name="servletConfig" />
            <interceptor-ref name="i18n" />
            <interceptor-ref name="chain" />

            <interceptor-ref name="scopedModelDriven" />
            <interceptor-ref name="modelDriven" />
            <interceptor-ref name="fileUpload">
                <param name="maximumSize">10485760</param>
            </interceptor-ref>
            <interceptor-ref name="checkbox" />
            <interceptor-ref name="staticParams" />
            <interceptor-ref name="params">
                <param name="excludeParams">dojo\..*</param>
            </interceptor-ref>
            <interceptor-ref name="json">
                <param name="enableSMD">true</param>
            </interceptor-ref>
            <interceptor-ref name="prepare" />
            <interceptor-ref name="conversionError" />
            <interceptor-ref name="businessException" />
            <interceptor-ref name="validation">
                <param name="includeMethods">save,search</param>
            </interceptor-ref>
            <interceptor-ref name="workflow">
                <param name="includeMethods">save,search</param>
            </interceptor-ref>
            <interceptor-ref name="tokenSession">
                <param name="includeMethods">save</param>
            </interceptor-ref>
        </interceptor-stack>

    </interceptors>
    <default-interceptor-ref name="defaultStack"/>

    <global-results>
        <result name="exception" type="chain">
            <param name="actionName">exception</param>
            <param name="namespace">/</param>
        </result>
        <result name="rethrowException">/applicationAccessDeniedPage.jsp</result>       
        <result name="applicationAccessDenied">/applicationAccessDeniedPage.jsp</result>
        <result name="unavailableResource">/unavailableResource.jsp</result>        
        <result name="pessimisticLock">/pessimisticLock.jsp</result>        
        <result name="goto-crud" type="redirect">/crud/index.action</result>
        <result name="goto-dict" type="redirect">/dictionaries/index.action</result>
        <result name="reportXls" type="poi-excel">
            <param name="contentDisposition">attachment; filename="${resultFileName}"</param>
            <param name="excelWorkbook">workbook</param>
        </result>

    </global-results>
    <global-exception-mappings>
        <exception-mapping exception="com.myhome.ap.service.exception.AuthorizationFailedException" result="rethrowException"/>
        <exception-mapping exception="com.myhome.ap.service.exception.ApplicationAccessDeniedException" result="applicationAccessDenied"/>
        <exception-mapping exception="org.hibernate.ObjectNotFoundException" result="unavailableResource" />
        <exception-mapping exception="com.myhome.ap.service.exception.model.EntityHasBeenDeletedException" result="unavailableResource" />
        <exception-mapping exception="com.myhome.ap.service.exception.PessimisticLockingException" result="pessimisticLock" />
        <exception-mapping exception="java.lang.Exception" result="exception"/>
     </global-exception-mappings>

    <action name="version" class="com.myhome.ap.web.action.VersionAction" />

</package>
</struts>

What am I doing wrong? Can you suggest me some good examples/tutorial how to do deserialization from JSON to Java in Struts2, because I cannot find even one correct full example with JSON deserialization in Struts2, specially example of Action code which will receive the JSON and bind it to Java.

我究竟做错了什么?你能给我推荐一些如何在 Struts2 中从 JSON 反序列化到 Java 的好例子/教程,因为我在 Struts2 中找不到一个正确的 JSON 反序列化完整例子,特别是 Action 代码的例子,它将接收 JSON 并将其绑定到 Java .

I am new in Struts at all, so that's why I have problems to understand some issues and flow, for example how to receive and handle JSON in Action. There are examples for serialization with struts2-json-plugin, but with this subject I had no trouble. Please help me...

我是 Struts 的新手,所以这就是为什么我在理解一些问题和流程方面遇到问题,例如如何在 Action 中接收和处理 JSON。有使用 struts2-json-plugin 进行序列化的示例,但是对于这个主题,我没有遇到任何麻烦。请帮我...

采纳答案by Roman

I figured it out. There was missing:

我想到了。有遗漏:

contentType: 'application/json',

in my Ajax request.

在我的 Ajax 请求中。