본문 바로가기

개발/Spring

[spring] org.springframework.validation.BindException 에러

반응형

- 나의 상황 

 : 기존에 잘 동작하던 화면에 새로운 기능을 추가하며 새 변수 하나가 추가되었는데.. 기존 페이지 요청 시 아래 에러 발생.

test 변수가 쓰일때는 js에서 value 값을 넣어주는데.. 문제가 없었음.. 근데 기존 기능들에 빈 값으로 넘어갈 때마다 오류 발생.

추가된 곳.
-testVo
int test;
-html
<input type="hidden" id="test" name="test" />
에러코드
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'testForm' on field 'test': rejected value []; 
codes [typeMismatch.testFrom.test,typeMismatch.test,typeMismatch.int,typeMismatch]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [testForm.test,test]; 
arguments []; 
default message [test]]; 
default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'test'; 
nested exception is java.lang.NumberFormatException: For input string: ""]

- 원인 

 : 스프링은 화면에서 넘어간 값이 empty string(빈 문자열, "")이거나 null일 때 변수에도 이 값을 그대로 할당하려고 시도하는데, 원시타입의 변수들은 empty string이나 null을 할당할 수 없기 때문에 타입 캐스팅 중에 에러가 발생하는 것이다. (참고 : https://noritersand.github.io/spring/spring-org-springframework-validation-bindexception/

-해결 

방법 1. 해당 값이 필요한 기능 요청시에만 JS 에서 동적으로 input 에 name값을 넣어줌. 

-> $("#test").attr("name","test");

방법 2. vo 에 선언된 int 타입이 null 을 할당할 수 없어서 발생한 문제이므로 int 타입 대신 Integer 타입을 선언.

-> testVo 에 'Integer test' 로 변경

 

 

반응형