-
[Spring MVC] 검증 - Spring 순수 ValidationSpring/Spring MVC 2021. 7. 18. 13:59
Validation V1
입력값 에러를 처리하기 위해 컨트롤러에 검증로직을 추가하였다
만약 에러가 발생하면 이를 HashMap에 저장하고 Model에 담아 뷰로 전달한다
if (item.getPrice() != null && item.getQuantity() != null) { int resultPrice = item.getPrice() * item.getQuantity(); if (resultPrice < 10000) { errors.put("globalError", "가격 * 수량의 합은 10,000원 이상이어야 합니다. 현재 값 = " + resultPrice); } }
<form action="item.html" th:action th:object="${item}" method="post"> <div th:if="${errors?.containsKey('globalError')}"> <p class="field-error" th:text="${errors['globalError']}">전체 오류 메시지</p> </div>
Validation V2
Spring은 에러를 저장하는 BindingResult객체를 제공한다
이 객체는 FieldError, ObjectError 객체를 저장하여 Model에 담긴다
(FieldError, ObjectError는 각각 필드 에러, 글로벌 에러를 저장한다)
이 객체를 사용하면 다음과 같이 수정된다
if (item.getPrice() != null && item.getQuantity() != null) { int resultPrice = item.getPrice() * item.getQuantity(); if (resultPrice < 10000) { bindingResult.addError(new ObjectError("item", "가격 * 수량의 합은 10,000원 이상이어야 합니다. 현재 값 = " + resultPrice)); } }
<form action="item.html" th:action th:object="${item}" method="post"> <div th:if="${#fields.hasGlobalErrors()}"> <p class="field-error" th:each="err : ${#fields.globalErrors()}" th:text="${err}">글로벌 오류 메시지</p> </div>
Validation V3
FieldError, ObjectError는 각각 RejectValue(), Reject() 함수를 사용함으로 대체할 수 있다
각각의 정의는 다음과 같다
void rejectValue(@Nullable String field, String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);
void reject(String errorCode, @Nullable Object[] errorArgs, @Nullable String defaultMessage);
객체 바로 뒤에 BindingResult가 존재하므로 어떤 객체를 검증하는 것인지 입력할 필요 없이 사용해도 된다
Validation V4
컨트롤러의 검증 부분을 따로 빼서 새로운 클래스로 등록하자
그리고 InitBinder에 해당 검증기를 등록하고 이를 사용하자
@InitBinder public void init(WebDataBinder dataBinder) { dataBinder.addValidators(itemValidator); }
@PostMapping("/add") public String addItemV6(@Validated @ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes) { if (bindingResult.hasErrors()) { return "validation/v2/addForm"; } }
@ModelAttribute 앞에 @Validated 붙여 InitBinder에 등록된 검증기를 먼저 실행한다
'Spring > Spring MVC' 카테고리의 다른 글
[Spring MVC] 로그인 처리 - 쿠키, 세션 (1) 2021.07.20 [Spring MVC] 검증 - Bean Validation (0) 2021.07.18 [Spring MVC] 메시지, 국제화 기능 (0) 2021.07.18 [Spring MVC] HTTP 메시지 컨버터 (0) 2021.05.22 [Spring MVC] HTTP 응답 메시지 만들기 (0) 2021.05.22