February 03, 2023
하지만 경우에 따라 컨트롤러에서 바로 해당 객체를 검증하지 않고 별도로 검증해야 하는 순간들이 있다.
javax.validation.*
의 객체를 사용한다.예를 들어 아래와 같은 Dto 객체가 있다고 하자.
public class UserDto {
public static class UserRequest {
@NotEmpty(message = "이름 정보는 필수입니다.")
private String name;
@NotEmpty(message = "이메일 정보는 필수입니다.")
private String email;
...(중략)...
}
}
public void checkValidation () {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<RequestDto.Member>> violations = validator.validate(memberDto);
StringBuilder stringBuilder = new StringBuilder();
for (ConstraintViolation<RequestDto.Member> violation : violations) {
stringBuilder.append(String.format("%s : %s \r\n", violation.getInvalidValue(), violation.getMessage()));
}
if (violations.size() > 0) {
log.error(stringBuilder.toString());
throw new CommonException(Errors.GENERAL_WRONG_PARAM);
}
}