스프링 부트에서는 기본적으로 Unknown Property는 Deserializaion(역직렬화) 중에 무시 된다.
입력 값 이외에 값이 들어왔을 때 에러(Bad Request)를 발생 시키기 위해서는 spring.jackson.deserialization.fail-on-unknown-properties=true 로 설정해야 한다.
입력 데이터 체크와 에러 메시지 출력
입력 데이터의 값이 이상한 경우 Bad_Request로 응답
비즈니스 로직으로 검사할 수 있는 에러
응답(response) 메시지에 에러에 대한 정보가 있어야 한다.
Java Bean Vaildation
데이터 검증을 위한 로직을 도메인 모델 자체에 묶어서 표현하는 방법이 있다.
Java Bean Vaildation 에서 데이터 검증을 위한 어노테이션 (Annotation)을 제공하고 있다.
Valid 어노테이션을 이용한 Validation 체크
@Vaild는 JSR-303이란 이름으로 채택된 서블릿 2.3 표준 스펙 중 하나이며, 스프링은 이 표준을 확장하고 쉽게 사용할 수 있도록 스프링만의 방식으로 재편성 해 주었다.
@NotNull, @NotEmpty, @Min, @Max, @Size(min=, max=) 사용해서 입력 값을 바인딩할 때 에러를 확인할 수 있다.
Errors ( BindingResult )는 항상 @Valid 바로 다음 인자로 사용해야 한다.
Custom Validation
Custom Validation 작성
Vaildator 클래스를 Spring Bean 컴포넌트로 정의한다.
@ComponentpublicclassEventValidator{publicvoidvalidate(EventDtoeventDto,Errorserrors){if(eventDto.getBasePrice()>eventDto.getMaxPrice()&&eventDto.getMaxPrice()!=0){//Field Error errors.rejectValue("basePrice","wrongValue","BasePrice is wrong");errors.rejectValue("maxPrice","wrongValue","MaxPrice is wrong");//Global Error errors.reject("wrongPrices","Values for prices are wrong");}LocalDateTimeendEventDateTime=eventDto.getEndEventDateTime();if(endEventDateTime.isBefore(eventDto.getBeginEventDateTime())||endEventDateTime.isBefore(eventDto.getCloseEnrollmentDateTime())||endEventDateTime.isBefore(eventDto.getBeginEnrollmentDateTime())){errors.rejectValue("endEventDateTime","wrongValue","EndEventDateTime is wrong");}}}
Custom Validation 사용
EventValidator 를 주입 받고, EventValidator의 validate() 메서드를 호출하고, Errors 객체에 에러가 포함되어 있는지 확인합니다.