Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle null values in spring expression language

I have the following code using spring expression language:

StandardEvaluationContext stdContext = new StandardEvaluationContext();
stdContext.setVariable("emp", filterInputData); 
ExpressionParser parser = new SpelExpressionParser();     
parser.parseExpression("#emp.?[name.toLowerCase().contains('Hari')]").getValue(stdContext);

where emp is the name of the bean. Here the name can be null and when calling name.toLowerCase() I am getting a nullpointer exception. How to handle the null values in this scenario? I need to call toLowercase() for only non-null values.

like image 799
user1293071 Avatar asked Jul 23 '12 08:07

user1293071


1 Answers

"#emp.name != null ? #emp.name.toLowerCase().contains('hari') : null"

or

"#emp.name != null ? #emp.name.toLowerCase().contains('hari') : false"

depending on what you want back when the name is missing.

Actually, this short form works too...

"#emp.name != null ? toLowerCase().contains('hari') : null"

BTW, in your original question...

name.toLowerCase().contains('Hari')

will never return true (H is upper case).

Or, Elvis is your friend...

Expression expression = new SpelExpressionParser().parseExpression("#emp.name?:'no name found'");
value = expression.getValue(context, String.class).toLowerCase();
like image 123
Gary Russell Avatar answered Oct 13 '22 19:10

Gary Russell