2013-05-09 4 views
1

저는 꽤 Java에 익숙해서 나와 함께 있습니다. 양식 데이터를 처리하고 오류 로그로 보내는 간단한 스크립트가 있습니다. 전화 필드가 채워지지 않은 경우 오류 로그로 보내지 않는다고 말하는 간단한 null 확인이 있습니다. 그러나 어떤 이유로 그것은 작동하지 않습니다. 따라서 오류 로그에 나타나는 것은 "계정과 관련된 전화 번호 :"문자열과 같습니다.빈 양식 필드에 대해 확인하십시오.

String phone = request.getParameter("phoneNumber"); 
String showPhone = (phone != null) ? " Phone number associated with account: " + phone : ""; 

log.error(showPhone); 
+0

이 보이는 ... –

+3

양식 데이터가 무엇인지 아무런 단서는 없지만 웹 앱에서 가져온 것이라면 빈 텍스트 필드는 null이 아니라 비어 있습니다. –

답변

3

은 당신이 사용중인 프레임 워크 모르겠지만, null 객체와 빈 문자열은 자바에서 동일하지 않습니다. 당신이 시도 할 수 있습니다 :

String showPhone = (phone != null && phone.trim().length()>0) ? " Phone number associated with account: " + phone : ""; 

&& phone.trim().length()>0이 (가) 문자열 내용이 있는지 확인합니다.

1

나는 당신이 사용하고자하는 StringUtils.isNotEmpty

StringUtils.isNotEmpty(null)  = false 
StringUtils.isNotEmpty("")  = false 
StringUtils.isNotEmpty(" ")  = true 
StringUtils.isNotEmpty("bob")  = true 
StringUtils.isNotEmpty(" bob ") = true 

또는 StringUtils.isNotBlank이 같이

StringUtils.isNotBlank(null)  = false 
StringUtils.isNotBlank("")  = false 
StringUtils.isNotBlank(" ")  = false 
StringUtils.isNotBlank("bob")  = true 
StringUtils.isNotBlank(" bob ") = true 

생각 : 'phone` 빈 문자열처럼

String phone = request.getParameter("phoneNumber"); 
String showPhone = StringUtils.isNotBlank(phone) ? " Phone number associated with account: " + phone : ""; 
+0

+1, StringUtils는 Apache commons-lang의 일부이며 표준 JavaSE 라이브러리에 포함되어 있지 않습니다. 제 3 자 라이브러리가 제어/제한되는 환경에서 실행하지 않는 한 대개 문제는 아닙니다. – FrustratedWithFormsDesigner

0
public bool isNullOrEmpty(String val){ 
return val==null||"".val.trim(); 
} 
관련 문제