반응형
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 김영한
- .orelseThrow
- n+1
- 쿠키란
- abap value in field Data Class error
- optional
- 필터의 정의
- @Controller
- 필터vs인터셉터
- 인터셉터의 정의
- application-properties
- jpa
- spring
- 쿠키의 정의
- 구글 보안 api 활용
- 세션의 정의
- Testcode
- controller
- springSecurityFilterChain 오류
- 401오류
- Validation
- spring MVC
- filter vs interceptor
- 세션이란
- java.lang.AssertionError
- BindingResult
- 세션vs쿠키
- MVC
- SpringMVC
- 유연한 컨트롤러1 - v5
Archives
- Today
- Total
ABAP DUMP ERROR 24시
Validator interface 활용하기 본문
반응형
# 인프런 김영한의 스프링 MVC 2편 - 백엔드 웹 개발 핵심 기술을 개인적으로 정리한 글입니다.
정리
1. Validator interface를 활용하고 implement 투입
2. valiation을 통한 코딩.
과거 개발했던 부분에는 유효성 검정을 하는 코드들이 들어있어 가시성이 좋지 않았다.
다음 오류를 확인하고 해결해주는 Validator를 분리하여 작성해서 가시성을 높히도록 하자.
// @PostMapping("/add")
// public String addItemV4(@ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes){
// log.info("objectName = {}", bindingResult.getObjectName());
// log.info("target = {}", bindingResult.getTarget());
//
//// ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "itemName", "required");
//
// if(!StringUtils.hasText(item.getItemName())){
// bindingResult.rejectValue("itemName", "required");
// }
//
// if(item.getPrice() == null || item.getPrice()< 1000 || item.getPrice() > 1000000){
// bindingResult.rejectValue("price", "range", new Object[]{1000, 1000000}, null);
// }
// if(item.getQuantity() == null || item.getQuantity() >10000){
// bindingResult.rejectValue("quantity", "max", new Object[]{9999}, null);
// }
//
// 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("errors={}", bindingResult);
// return "validation/v2/addForm";
// }
// Item savedItem = itemRepository.save(item);
// redirectAttributes.addAttribute("item", savedItem.getId());
// redirectAttributes.addAttribute("status", true);
// return "redirect:/validation/v2/items/{itemId}";
// }
살펴보기
핵심기술
1.Bean을 통해 관리하기 위해 @Component를 사용.
@Component
2. Validator interface를 implement하기
@Component
public class ItemValidator implements Validator {
3. supports 와 validate 를 override 하기
@Override
public boolean supports(Class<?> clazz) {
return Item.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
support 부분을 까보니 DataBinder 가 존재하는데 아마 이부분에서 사용되는게 아닐까 싶다.. 더 공부하자
Item클래스를 isAssignableFrom 해서 class에게 파라미터를 넘겨주자.
validate 부분에는 bindingResult 대신 errors를 넣어주자.
코드를 까보면, Errors는 BindingResult와 상속관계에 존재함을 알수 있었다.
@Override
public void validate(Object target, Errors errors) {
Item item = (Item) target;
if(!StringUtils.hasText(item.getItemName())){
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);
}
}
}
4. Controller에 itemValidator를 ComponentScan이 대상이 되도록 설정.
그리고 다음과 같이 itemValiator.validate(item, bindingResult) 를 통해 활성화 시킨다.
private final ItemValidator itemValidator;
@InitBinder
public void init(WebDataBinder dataBinder){
log.info("init binder={}", dataBinder);
dataBinder.addValidators(itemValidator);
}
@PostMapping("/add")
// public String addItemV5(@ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes){
//
// itemValidator.validate(item, bindingResult);
//
// if (bindingResult.hasErrors()){
// log.info("errors={}", bindingResult);
// return "validation/v2/addForm";
// }
// Item savedItem = itemRepository.save(item);
// redirectAttributes.addAttribute("itemId", savedItem.getId());
// redirectAttributes.addAttribute("status", true);
// return "redirect:/validation/v2/items/{itemId}";
//
// }
반응형
'[WEB]Back-end > Spring MVC' 카테고리의 다른 글
[SpringMVC 2편] 필터 vs 인터셉터 (로그인 적용) (0) | 2022.02.28 |
---|---|
[SpringMVC 2편] Login 기능 추가하기. (0) | 2022.02.25 |
BindingResult , add FieldError=-> rejectValue 변환 (0) | 2022.02.21 |
BindingResult Version3 properties를 활용한 동적 변경 (0) | 2022.02.20 |
BindingResult를 활용한 Validation 처리 [전 vs 후(version1,2) ] (0) | 2022.02.19 |
Comments