Search
〰️

Validator 사용 (@Validated)

Validator

기존 Controller에서 사용하던 검증 로직을 별도의 Validator로 분리
@Component public class ItemValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Item.class.isAssignableFrom(clazz); // item == clazz // item == subItem(자식) } @Override public void validate(Object target, Errors errors) { Item item = (Item) target; // errors는 BindingResult의 부모클래스 // 검증 로직 if (!StringUtils.hasText(item.getItemName())) { errors.rejectValue("itemName", "required") ; } if (item.getPrice() == null || item.getPrice() < 10000 || item.getPrice() > 1000000) { errors.rejectValue("price", "range", new Object[]{1000, 1000000}, null); } if (item.getQuantity() == null || item.getQuantity() >= 9000) { errors.rejectValue("quantity", "max", new Object[]{9999}, null); } // 특정 필드가 아닌 복합 룰 검증 if (item.getPrice() != null && item.getQuantity() != null) { int resultPrice = item.getPrice() * item.getQuantity(); if (resultPrice < 10000) { errors.reject("totalPriceMin", new Object[]{10000, resultPrice}, null); } } } }
Java
복사

DataBinder + Validator

@InitBinder public void init(WebDataBinder dataBinder) { dataBinder.addValidators(itemValidator); // Controller가 호출될 때마다 WebDataBinder를 호출 -> 검증기를 적용 } public String addItemV6(@Validated @ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) { ... }
Java
복사
@Validated는 검증기를 실행하라는 의미의 어노테이션이다.
이 애노테이션이 붙으면 앞서 WebDataBinde에 등록한 검증기를 찾아서 실행한다. 그런데 여러 검증기를 등록한다면 그 중에 어떤 검증기가 실행되어야 할지 구분이 필요하다. 이때 supports() 가 사용된다.
여기서는 supports(Item.class) 가 호출되고, 결과가 true 이므로 ItemValidator 의 validate() 가 호출된다.
해당 컨트롤러에만 국한되어 적용된다.
@Valid 도 사용가능하다! (자바 표준 검증 애노테이션)