【问题标题】:Cannot read boolean property 'isEmpty' on bean无法读取 bean 上的布尔属性“isEmpty”
【发布时间】:2016-01-25 12:08:29
【问题描述】:

在jsp中显示一个Java bean的boolean属性时遇到了一个奇怪的问题。似乎名为 isEmpty() 的 getter 会在 EL 解析器上导致 ParseException。

出于演示目的,我创建了一个显示问题的类。

public class Bookcase {

    public boolean isWithoutContent() {

        return true;
    }

    public boolean isEmpty() {

        return true;
    }

}

调用jsp中的属性:

${bookcase.withoutContent}

${bookcase.empty}

第一个显示true,而第二个抛出错误:

org.apache.el.parser.ParseException: Encountered " "empty" "empty "" 
at line 1, column 23.

Was expecting:
    <IDENTIFIER> ...

现在我知道有一个 EL empty 运算符,但很明显,点运算符表明我在 bookcase 对象上调用 isEmpty() 方法?显然不是,考虑到错误。

在实际的 bean 上,我不能/不想重命名 isEmpty() 方法,但是如何在 jsp 中显示此属性?

【问题讨论】:

    标签: jsp el


    【解决方案1】:

    empty 是 EL 中的一个特殊关键字,它基本上检查是否为空和空。通常如下使用:

    <c:if test="${empty bean.object}"> <!-- if (object == null) -->
    <c:if test="${empty bean.string}"> <!-- if (string == null || string.isEmpty()) -->
    <c:if test="${empty bean.collection}"> <!-- if (collection == null || collection.isEmpty()) -->
    <c:if test="${empty bean.map}"> <!-- if (map == null || map.isEmpty()) -->
    <c:if test="${empty bean.array}"> <!-- if (array == null || array.length == 0) -->
    

    但是,您将它用作 bean 属性并且 EL 感到困惑。 EL specification 禁止使用 EL 关键字和 Java 标识符作为 bean 属性名称:

    1.17 保留字

    以下单词是为语言保留的,不得用作标识符。

    and   eq     gt     true   instanceof
    or    ne     le     false  empty
    not   lt     ge     null   div        mod
    

    请注意,其中许多词现在不在语言中,但将来可能会出现,因此开发人员必须避免使用这些词。

    您需要重命名它,或者使用${bean['empty']} 中的大括号表示法,或者作为完全不同的替代方法,让您的Bookcase 实现例如Collection接口,这样就可以直接使用${empty bookcase}了。

    另见:

    【讨论】:

      【解决方案2】:

      毕竟这很简单:

      ${bookcase['empty']}
      

      但它仍然让我感到困惑,为什么在点符号中使用 empty 就像保留字一样。

      【讨论】:

        猜你喜欢
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2013-11-14
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多