코드 그라데이션

BindingResult 두 번째 본문

Spring/Validation

BindingResult 두 번째

완벽한 장면 2024. 2. 22. 20:14

BindingResult 두 번째

  • 스프링이 제공하는 검증 오류를 보관하는 객체이다. 검증 오류가 발생하면 여기에 보관하면 된다.
  • BindingResult 가 있으면 @ModelAttribute 에 데이터 바인딩 시 오류가 발생해도 컨트롤러가 호출된다!

 

~~~~~ errors=org.springframework.validation.BeanPropertyBindingResult: 2 errors
Field error in object 'item' on field 'price': rejected value [yyyy]; codes [typeMismatch.item.price,typeMismatch.price,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [item.price,price]; arguments []; default message [price]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'price'; nested exception is java.lang.NumberFormatException: For input string: "yyyy"]
Field error in object 'item' on field 'price': rejected value [null]; codes []; arguments []; default message [가격은 1,000 ~ 1,000,000 까지 허용합니다.]

이 경우는

에러 페이지 나온다.

 

 

 

주의

  • BindingResult는 검증할 대상 바로 다음에 와야한다. 순서가 중요하다.
    예를 들어서 @ModelAttribute Item item, 바로 다음에 BindingResult 가 와야 한다.
  • BindingResult는 Model에 자동으로 포함된다.

 

BindingResult와 Errors

 

그런데 오류가 발생하는 경우 고객이 입력한 내용이 모두 사라진다. 이 문제를 해결해보자.

 

다음 포스팅에서...

 

728x90

'Spring > Validation' 카테고리의 다른 글

오류 코드와 메시지 처리 (1)  (0) 2024.02.24
FieldError와 ObjectError  (0) 2024.02.23
BindingResult 첫 번째  (0) 2024.02.22
프로젝트 준비 V2  (0) 2024.02.21
검증 직접 처리  (0) 2024.02.20
Comments