2012-07-23 63 views
7

空值我有使用彈簧表達式語言以下代碼:手柄在彈簧表達式語言

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

其中EMP是bean的名稱。這裏的名字可以爲空,當調用name.toLowerCase()時,我得到一個空指針異常。如何在這種情況下處理空值?我只需要調用toLowercase()以獲取非空值。

+1

'toLowerCase()。包含( '哈日')'總是'FALSE' – OrangeDog 2017-09-19 15:45:35

回答

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

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

取決於你想要回來的時候名失蹤。

其實,這種短形式的作品太...

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

順便說一句,在你原來的問題...

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

永遠不會返回true(H爲大寫)。

或者,貓王是你的朋友?

Expression expression = new SpelExpressionParser().parseExpression("#emp.name?:'no name found'"); 
value = expression.getValue(context, String.class).toLowerCase(); 
+0

嗨,你的答案非常感謝。在我的情況下,員工是對象的集合。所以我需要從集合中獲取名稱。我嘗試過使用「#emp。?[name!= null?toLowerCase()。contains('hari'):null]」,但它不起作用,並且我收到一條消息,指出EmployeeDto中不存在toLowercase方法,請你幫我解決這個問題。非常感謝 – user1293071 2012-07-23 13:30:45

+0

不確定您爲什麼試圖使用集合選擇。 「#emp ['name']!= null?#emp ['name']。toLowerCase()。contains('hari'):false」 – 2012-07-23 21:07:01

+0

它工作正常,非常感謝您的支持,並幫助我找到解決方案 – user1293071 2012-07-25 04:05:36

0

你可以將這個bean自動裝配到你的班級嗎?

喜歡的東西:

public class YourClass{ 
    @Autowire 
    private Employee emp 

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