Spring에서 유효성을 검사하는 방법
- Spring Validator 구현
- Bean Validation
- Bean Validation 1.0(JSR-303)
- Bean Validation 1.1(JSR-349)
- Bean Validation 2.0(JSR-380)
두 가지 방법 중 Validator 인터페이스를 구현하여 유효성 검사하는 방법을 알아보겠습니다.
Validator 인터페이스
org.springframework.validation.Validator
public class Person {
private String name;
private int age;
// the usual getters and setters...
}
public class PersonValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Person.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name", "empty");
Person person = (Person) target;
if (person.getAge() < 0) {
errors.rejectValue("age", "Under 0");
} else if (person.getAge() > 120) {
errors.rejectValue("age", "Over 120");
}
}
}
spring 공식사이트의 예제를 가져왔습니다.
- supports 메서드 : 파라미터로 전달된 클래스의 검증가능 여부
- validate 메서드 : 파라미터로 전달된 객체를 검증, 실패하면
org.springframework.validation.Errors
객체에 에러 등록
반응형
'Spring' 카테고리의 다른 글
[Tomcat] 톰캣 로그 한글에서 영어로 바꾸는 방법 (0) | 2020.06.26 |
---|---|
IntelliJ에서 SpringMVC + Maven + Tomcat (0) | 2020.06.26 |
[Homebrew] Homebrew로 톰캣 설치시 환경변수 (0) | 2020.06.22 |
[오류] Port already in use: 1099 (0) | 2020.06.22 |
[Spring] Spring Boot H2 Database Console 사용하기 (0) | 2020.06.21 |