4

I encountered a strange problem when displaying a boolean property of a Java bean in jsp. It appears that a getter called isEmpty() causes a ParseException on the EL parser.

For demonstration purposes I created a class that shows the problem.

public class Bookcase {

    public boolean isWithoutContent() {

        return true;
    }

    public boolean isEmpty() {

        return true;
    }

}

Calling on the properties in jsp:

${bookcase.withoutContent}

${bookcase.empty}

The first shows true while the second throws an error:

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

Was expecting:
    <IDENTIFIER> ...

Now I know there's an EL empty operator but clearly the dot operator suggests I'm invoking the isEmpty() method on the bookcase object? Well apparently not, considering the error.

On the actual bean I cannot / do not want to rename the isEmpty() method, but how do I display this property in jsp?

Richard Osseweyer
  • 1,693
  • 20
  • 25

2 Answers2

4

empty is a special keyword in EL which basically checks for nullness and emptiness. It's usually to be used like below:

<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) -->

However, you was using it as a bean property and EL got confused. Using EL keywords and Java identifiers as bean property names is forbidden by EL specification:

1.17 Reserved Words

The following words are reserved for the language and must not be used as identifiers.

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

Note that many of these words are not in the language now, but they may be in the future, so developers must avoid using these words.

You'd need to either rename it, or to use the brace notation as in ${bean['empty']}, or as a completely different alternative let your Bookcase implement e.g. Collection interface, so that you can just use ${empty bookcase}.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

Well after all it was simple:

${bookcase['empty']}

But still it confuses me why using empty in the dot notation acts like a reserved word.

Richard Osseweyer
  • 1,693
  • 20
  • 25