DWR 报告转换器错误,将 null 从 Javascript 传递到 Java 类

DWR reporting converter error when passing null from Javascript to Java class

本文关键字:Javascript Java null 转换器 报告 错误 DWR      更新时间:2023-09-26

在我的Java EE Web应用程序中,我使用DWR(Direct Web Remoting)进行Ajax。

Java 类有许多 int 成员,可以通过 DWR 将其转换为 JavaScript 对象。例如:

// Java
public class MyClass {
    private int id;
    private String comments;
}
// the converted JavaScript class
var myObject = {
    id: 100,
    comments: "hello world"
}

但是,当我尝试将 id 等于 null 的 js 对象发送到应用程序服务器时,DWR 报告了以下异常:

Erroring: batchId[7] message[org.directwebremoting.extend.MarshallException: Error marshalling int: Format error converting null. See the logs for more details.]

任何人都可以帮助提出任何想法吗?

在 Java 中,int 是一种值类型,而不是引用类型。因此,它永远无法null分配值。另一方面,Javascript使用动态类型。每个变量都可以更改其类型,因此您可以将 null 分配给所有变量。DWR 处理生成错误的情况。

您有以下几种选择:

如果您需要处理此值在服务器端可以为 null 的事实(看起来确实如此),您可以使用引用类型,例如 Integer ,而不是 int 。否则,只需确保始终为 Javascript id成员分配一个值即可

另一种选择:如果缺少javascript对象的值,也许DWR允许分配默认值。