Spring Expression Language (SpEL): check empty string?

Viewed 7015
3 Answers

This is how it's done according to latest documentation:

not null or empty #myString > ''

null or empty #myString <= ''

not null or blank #myString?.trim() > ''

null or blank #myString?.trim() <= ''

You can call any Java method on an object, e.g. #myString.length(), #myString.isEmpty() or #myString.isBlank(). I'd say, that would be the canonical way to check whether a string is empty or blank.

For null or empty: #myString == null || #myString.isEmpty()

For null or blank: #myString == null || #myString.isBlank()

You can test this with:

System.out.println(new SpelExpressionParser().parseExpression("#root?.isEmpty()").getValue("x")); // false
System.out.println(new SpelExpressionParser().parseExpression("#root?.isEmpty()").getValue("")); // true
System.out.println(new SpelExpressionParser().parseExpression("#root?.isEmpty()").getValue((Object) null)); // null
System.out.println(new SpelExpressionParser().parseExpression("#root == null || #root.isEmpty()").getValue("x")); // false
System.out.println(new SpelExpressionParser().parseExpression("#root == null || #root.isEmpty()").getValue("")); // true
System.out.println(new SpelExpressionParser().parseExpression("#root == null || #root.isEmpty()").getValue((Object) null)); // true
   /*
    list=['a','b']
    list=[]
    list=""
   */
   ${empty list}//false
   ${empty list1}//true
   ${empty list2}//true
Related