Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

BindingResult1 본문

인프런/[인프런] 스프링 MVC 2

BindingResult1

Seung__ 2021. 9. 24. 18:22

지금부터 스프링이 제공하는 검증 오류 처리 방법 중  BindingResult를 알아보자.

 

 

1. 변경 전

    @PostMapping("/add")
    public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes, Model model) {

        //검증 오류 결과를 보관
        Map<String, String> errors= new HashMap<>();

        //검증 로직
        if(!StringUtils.hasText(item.getItemName())){
            errors.put("itemName", "상품 이름을 필수 입니다.");
        }

    }

 

 

2. BindingResult 적용


 @PostMapping("/add")
    public String addItemV1(@ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
    ....
    }
  • BindingResult bindingResult 파라미터의 위치는 @ModelAttribute Item item 다음에 와야 한다.
  • 왜냐? Item 객체의 바인딩 결과를 담고 있기 때문. 순서가 중요함.
  • BindingResult가 기존의 Map<String,String> errors를 대체한다.

 

 

 

3. FieldError 처리


if(!StringUtils.hasText(item.getItemName())){
  //errors.put("itemName", "상품 이름을 필수 입니다.");
  bindingResult.addError(new FieldError("item", "itemName", "상품 이름은 필수 입니다."));
}
  • FieldError의 경우 BindingResult에 FieldError를 추가하면 된다.
  • public FieldError(String objectName, String field, String defaultMessage) {
    		this(objectName, field, null, false, null, null, defaultMessage);
    	}
    • object : @ModelAttribute에 담기는 객체 이름.
    • field : 오류 발생하는 필드 이름
    • deafultMessgae : 오류 기본 메시지.

 

 

 

4. global Error - ObjectError


        //특정 필드가 아닌 복합 룰 검증
        if(item.getPrice() != null && item.getQuantity() != null){
            int resultPrice = item.getPrice() * item.getQuantity();
            if(resultPrice < 10000){
                //errors.put("globalError", "가격 * 수량은 10,000원 이상이어야 합니다. 현재 값 = " + resultPrice);
                bindingResult.addError(new ObjectError("item", "가격 * 수량은 10,000원 이상이어야 합니다. 현재 값 = " + resultPrice));
            }
        }
  • globalError는 ObjectError로 대체가능하다.
  • objectName : @ModelAttribute 의 이름
  • defaultMessage : 오류 기본 메시지

 

 

5.Thymeleaf의 스프링 검증 오류 통합


  • #fields : #fields 로 BindingResult 가 제공하는 검증 오류에 접근할 수 있다.
        <div th:if="${#fields.hasGlobalErrors()}">
            <p class="field-error" th:each="err : ${#fields.globalErrors()}" th:text="${err}">global error message</p>
        </div>
  • th:errors : 해당 필드에 오류가 있는 경우에 태그를 출력한다. th:if 의 편의 버전이다. error Message를 찾아서 출력.
  • th:errorclass : th:field 에서 지정한 필드에 오류가 있으면 class 정보를 추가한다.
        <div>
            <label for="itemName" th:text="#{label.item.itemName}">상품명</label>
            <input type="text" id="itemName" th:field="*{itemName}"
                   th:errorclass="field-error" class="form-control" placeholder="이름을 입력하세요">
            <div class="field-error" th:errors="*{itemName}">
                상품명 오류
            </div>
        </div>
  • 전체.
<div class="container">

    <div class="py-5 text-center">
        <h2 th:text="#{page.addItem}">상품 등록</h2>
    </div>

    <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}">global error message</p>
        </div>

        <div>
            <label for="itemName" th:text="#{label.item.itemName}">상품명</label>
            <input type="text" id="itemName" th:field="*{itemName}"
                   th:errorclass="field-error" class="form-control" placeholder="이름을 입력하세요">
            <div class="field-error" th:errors="*{itemName}">
                상품명 오류
            </div>
        </div>
        <div>
            <label for="price" th:text="#{label.item.price}">가격</label>
            <input type="text" id="price" th:field="*{price}"
                   th:errorclass="field-error" class="form-control" placeholder="가격을 입력하세요">
            <div class="field-error" th:errors="*{price}">
                가격 오류
            </div>
        </div>
        <div>
            <label for="quantity" th:text="#{label.item.quantity}">수량</label>
            <input type="text" id="quantity" th:field="*{quantity}"
                   th:errorclass="field-error" class="form-control" placeholder="수량을 입력하세요">
            <div class="field-error" th:errors="*{quantity}">
                수량 오류
            </div>
        </div>

        <hr class="my-4">

        <div class="row">
            <div class="col">
                <button class="w-100 btn btn-primary btn-lg" type="submit" th:text="#{button.save}">상품 등록</button>
            </div>
            <div class="col">
                <button class="w-100 btn btn-secondary btn-lg"
                        onclick="location.href='items.html'"
                        th:onclick="|location.href='@{/validation/v2/items}'|"
                        type="button" th:text="#{button.cancel}">취소</button>
            </div>
        </div>

    </form>

</div> <!-- /container -->

 

 

6. GitHub : 210924 BindingResult1


 

GitHub - bsh6463/Validation-V1

Contribute to bsh6463/Validation-V1 development by creating an account on GitHub.

github.com

 

'인프런 > [인프런] 스프링 MVC 2' 카테고리의 다른 글

FieldError, ObjectError  (0) 2021.09.24
BindingResult2  (0) 2021.09.24
검증 직접 처리, validation  (0) 2021.09.24
검증 요구사항.  (0) 2021.09.24
WebApplication 국제화 적용  (0) 2021.09.24
Comments