16

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.

1
  • 4
    toLowerCase().contains('Hari') is always false Commented Sep 19, 2017 at 15:45

2 Answers 2

37
"#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();
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, Many thanks for your answer. In My case, The employee is a collection of object. So I need to get the name from the collection . I tried with "#emp.?[name != null ? toLowerCase().contains('hari') : null]" , but it is not working and I am getting an message saying that the toLowercase method does not exist in EmployeeDto, Could you please help me to fix this issue. Many thanks
Not sure why you are trying to use collection selection. If your collection is a map, this works fine... "#emp['name'] != null ? #emp['name'].toLowerCase().contains('hari') : false"
It worked, Many thanks for your support and helping me to find a solution
It feels like name?.toLowerCase() should also help
-1

Can you Autowire this bean to your class?

Something like:

public class YourClass{ 
    @Autowire
    private Employee emp

    public boolean func(){
        if (emp.getName() != null){
            return emp.getName().toLowerCase().contains('Hari');
        }else{
            return false;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.