타임리프를 사용하면서 페이지 렌더링 시 map으로 데이터를 받을 때, map에 데이터가 null 일 경우 화면에 노출을 하지 않고,
null이 아닐 경우에는 화면에 어떤 방식으로 노출 할 지 분기 처리 하는 문법에 대해서 기록해보았다!!
//검증 로직
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";
}
<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')}
th:class="${errors?.containsKey('itemName')} ? 'form-control field-error' : 'form-control'"