hrming
[Spring] Validation & BindingResult 본문
① Validator 클래스를 작성한 후,
② Controller단에서 BindingResult를 사용해 에러 체크 & 그에 따른 처리
Validation by Using Spring’s Validator Interface
The next example provides validation behavior for the Person class by implementing the following two methods of the org.springframework.validation.Validator interface:
- supports(Class): Can this Validator validate instances of the supplied Class?
- validate(Object, org.springframework.validation.Errors): Validates the given object and, in case of validation errors, registers those with the given Errors object.
Implementing a Validator is fairly straightforward, especially when you know of the ValidationUtils helper class that the Spring Framework also provides. The following example implements Validator for Person instances:
public class PersonValidator implements Validator {
/**
* This Validator validates only Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() < 0) {
e.rejectValue("age", "negativevalue");
} else if (p.getAge() > 110) {
e.rejectValue("age", "too.darn.old");
}
}
}
출처 및 참고:
https://docs.spring.io/spring-framework/reference/core/validation/validator.html
Validation by Using Spring’s Validator Interface :: Spring Framework
Spring features a Validator interface that you can use to validate objects. The Validator interface works by using an Errors object so that, while validating, validators can report validation failures to the Errors object. Implementing a Validator is fairl
docs.spring.io
BindingResult
- 스프링이 제공하는 검증 오류 처리 방법 / 검증 오류를 보관하는 객체
- 검증 오류가 발생하면 BindingResult 객체에 보관
- BindingResult가 있으면 @ModelAttribute에 데이터 바인딩 오류가 발생했을 때, BindingResult에 오류 정보가 담기게 되고 Controller 쩡상 호출
- Binding Reult가 없으면 Controller가 호출되지 않고 Error Page로 이동
출처 및 참고:
https://hhhhicode.tistory.com/6
Validation 검증 - BindingResult 사용
이전 글로 BindingResult에 대해 알아보았습니다. Validation 검증 - BindingResult란? 이전 글로 Validation 검증이란? 에 대해 알아봤습니다. Validation 검증 - 검증이란? Validation을 하는 이유 폼 입력 시 검증 오
hhhhicode.tistory.com
'Spring' 카테고리의 다른 글
[Spring] Spring Security - Form login (0) | 2024.03.15 |
---|---|
[Spring] Spring Security (0) | 2024.03.14 |
[Spring] @Component (0) | 2024.03.04 |
VO(Value Object) (0) | 2022.08.18 |
Spring DI (0) | 2022.05.31 |