728x90
- Bean Validation에서 특정 필드( FieldError )가 아닌 해당 오브젝트 관련 오류( ObjectError )는 어떻게 처리할 수 있을까?
- @ScriptAssert()를 사용하면 된다
@Data
@ScriptAssert(lang = "javascript", script = "_this.price * _this.quantity >= 10000", message = "총 합이 10000원 넘게 입력해주세요")
//현업에서는 기능이 약해 많이 사용하지 않는다
public class Item {
}
- 메시지 코드 생성
- ScriptAssert.item
- ScriptAssert
- 실제 사용해보면 제약이 많고, 복잡하다.
- 실무에서는 검증 기능이 해당 객체의 범위를 넘어서는 경우도 종종 등장하므로 그런 대응을 하기 어렵다
- 따라서 Object 오류 같은경우 Java 코드로 작성하는 것을 권장한다.
@PostMapping("/add")
public String addItem(@Validated @ModelAttribute Item item, BindingResult bindingResult,
RedirectAttributes redirectAttributes, Model model) { //@Validated를 적어주면 정상적으로 어노테이션이 동작한다
//@Validated가 있으면 글로벌 Validator가 동작해서 어노테이션 기반 검증을 한다
//특정 필드가 아닌 복합 룰 검증
if (item.getPrice() != null && item.getQuantity() != null) {
int resultPrice = item.getPrice() * item.getQuantity();
if (resultPrice < 10000) {
bindingResult.reject("totalPriceMin", new Object[]{10000, resultPrice}, null);
}
}
if (bindingResult.hasErrors()) {
log.info("bindingResult = {}", bindingResult);
return "validation/v3/addForm";
}
//성공 로직
Item savedItem = itemRepository.save(item);
redirectAttributes.addAttribute("itemId", savedItem.getId());
redirectAttributes.addAttribute("status", true);
return "redirect:/validation/v3/items/{itemId}";
}728x90
'스프링 MVC 2편(백엔드 웹 개발 활용 기술)' 카테고리의 다른 글
| Ch05. 검증(Bean Validation) - Bean Validation(groups) (0) | 2022.03.16 |
|---|---|
| Ch05. 검증(Bean Validation) - Bean Validation(수정 & 한계) (0) | 2022.03.16 |
| Ch05. 검증(Bean Validation) - Bean Validation(에러 코드) (0) | 2022.03.16 |
| Ch05. 검증(Bean Validation) - Bean Validation(스프링 적용) (0) | 2022.03.16 |
| Ch05. 검증(Bean Validation) - Bean Validation(시작) (0) | 2022.03.16 |