글로벌 범위 Validator: 모든 컨트롤러에 적용
컨트롤러 범위 Validator: 단일 컨트롤러에 적용
[ 설정 요소 ]
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public Validator getValidator() {
return new RegisterRequestValidator();
}
...
}
NOTE
@Valid 사용하기 위해 의존을 추가하자.implementation 'org.springframework.boot:spring-boot-starter-validation'
@PostMapping("/register/step3")
public String handleStep3(@Valid RegisterRequest regReq, Errors errors){
if(errors.hasErrors())
return "register/step2";
try{
memberRegisterService.regist(regReq);
return "register/step3";
} catch(DuplicateMemberException ex){
errors.rejectValue("email", "duplicate");
return "register/step2";
}
}
@Valid 붙이면 글로벌 범위 Validator가 해당 타입을 검증할 수 있는지 확인.Errors에 저장.[ 주의 사항 ]
Errors 타입 파라미터가 없으면 검증 실패 시 400 에러 응답 뜸!
RegisterRequestValidator 클래스는 RegisterRequest 타입만 검증 가능.
따라서, 글로벌 범위 Validator로 부적합.
스프링 MVC는 자체적으로 글로벌 Validator 제공해서 이를 이용해 Bean Validation이 제공하는 애노테이션으로 값 검증이 가능.
이는 추후에...
@initBinder를 이용해 컨트롤러 범위 Validator 설정.
@PostMapping("/register/step3")
public String handleStep3(@Valid RegisterRequest regReq, Errors errors){
if(errors.hasErrors())
return "register/step2";
try{
memberRegisterService.regist(regReq);
return "register/step3";
} catch(DuplicateMemberException ex){
errors.rejectValue("email", "duplicate");
return "register/step2";
}
}
@InitBinder
protected void initBinder(WebDataBinder binder){
binder.setValidator(new RegisterRequestValidator());
}
initBinder()가 결정.setValidator()를 이용해 컨트롤러 범위에 적용할 Validator 설정.
WebDataBinder는 내부적으로 Validator 목록을 갖음.- 이 목록에는 글로벌 범위 Validator가 기본으로 포함.
setValidator()를 하면 기존 Valiteor 목록을 삭제하고 파라미터로 전달받은 Validator를 목록에 추가
=> 글로벌 범위 Validator 대신 컨트롤러 범위 Validator 사용.
addValidator()는 기존 Validator 목록에 새로운 Validator 추가.
즉, 글로벌 범위 Validator 존재할 때 실해하면, 새로운 추가 컨트롤러 범위 Validator가 기존꺼 뒤에 추가됨.