Validator 분리
@Component
public class ItemValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
// Item 및 Item의 자식의 타입인지 확인한다.
// 자식까지 확인하기 위해 isAssignableFrom()을 쓴다.
return Item.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
// Object 타입이기 때문에 캐스팅을 해야 한다.
Item item = (Item) target;
if (!StringUtils.hasText(item.getItemName())) {
// Errors의 자식이 BidingResult라서 담을 수 있다.
errors.rejectValue("itemName", "required");
}
if (item.getPrice() == null || item.getPrice() < 1000 || item.getPrice() > 1000000) {
errors.rejectValue("price", "range", new Object[]{1000, 1000000}, null);
}
if (item.getQuantity() == null || item.getQuantity() > 10000) {
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);
}
}
}
}WebDataBinder
동작 방식
글로벌 설정
참고
Last updated