타임리프 조건절 노출 처리

정병웅·2024년 5월 25일
0

front-end

목록 보기
3/3
타임리프를 사용하면서 페이지 렌더링 시 map으로 데이터를 받을 때, map에 데이터가 null 일 경우 화면에 노출을 하지 않고, 
null이 아닐 경우에는 화면에 어떤 방식으로 노출 할 지 분기 처리 하는 문법에 대해서 기록해보았다!!

상황

  1. 아이템을 등록하는 페이지는 상품이름, 가격, 수량을 입력 받는다.
  2. 각 input 입력에는 아래와 같이 조건이 있다.
    2.1. 상품 이름은 빈값이면 안된다.
    2.2. 가격은 1,000 ~ 1,000,000 까지 허용 한다.
    2.3. 수량은 최대 9,999 까지 허용합니다.
  3. 조건을 만족 하지 못할 경우 아래와 같이 화면에 유효성 검증 실패를 노출한다.

서버 검증 코드

//검증 로직
        if (!StringUtils.hasText(item.getItemName())) errors.put("itemName", "상품 이름은 필수 입니다.");
        if (item.getPrice() == null || item.getPrice() > 1000 || item.getPrice() < 10000000)
            errors.put("price", "가격은 1,000 ~ 1,000,000 까지 허용합니다.");
        if (item.getQuantity() == null || item.getQuantity() >= 9999)
            errors.put("quantity", "수량은 최대 9,999 까지 허용합니다.");

        //특정 필드가 아닌 복합 룰 검증
        if (item.getPrice() != null | item.getQuantity() != null) {
            int result = item.getPrice() * item.getQuantity();
            if (result < 10000) 
            errors.put("globalError", "가격 + 수량의 합은 10,000원 이상이어야합니다.현재 값 : " + result);
        }

        //검증에 실패하면 다시 입력 폼으로
        if (!errors.isEmpty()) {
            model.addAttribute("errors", errors);
            log.info("에러 출력 내용 : {}", errors);
            return "validation/v1/addForm";
        }

설명

  • 검증이 실패할 경우 실패 이유를 errors(Map 타입)에 넣고 model로 화면에 전달
  • 이때 map의 키값은 thymeleaf 에서 전달 받을 key 값과 동일해야함!

타임리프 코드

<div th:if="${errors?.containsKey('globalError')}">
            <p class="field-error" th:text="${errors['globalError']}">전체 오류 메시지</p>
</div>

<div>
     <label for="itemName" th:text="#{label.item.itemName}">상품명</label>
     <input type="text" id="itemName" th:field="*{itemName}"
                   th:class="${errors?.containsKey('itemName')} ? 'form-control field-error' : 'form-control'"
                   class="form-control" placeholder="이름을 입력하세요">
     <div class="field-error" th:if="${errors?.containsKey('itemName')}" th:text="${errors['itemName']}">
                상품명 오류
     </div>
</div>
        

설명

th:if="${errors?.containsKey('globalError')}

  • errors가 null이 아니고, 'globalError' 값이 있으면 해당 로직을 수행하는 의미이다.

th:class="${errors?.containsKey('itemName')} ? 'form-control field-error' : 'form-control'"

  • errors가 null이 아니고, 'itemName' 에 값이 존재하면 field-error 영역을 노출 하라는 의미이다.
profile
인생은 IT 노가다

0개의 댓글