springboot_validation : v1

This commit is contained in:
haerong22
2021-07-14 21:56:07 +09:00
parent 743a93731c
commit ef019cde62
2 changed files with 58 additions and 4 deletions

View File

@@ -5,10 +5,13 @@ import hello.itemservice.domain.item.ItemRepository;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
@Controller @Controller
@RequestMapping("/validation/v1/items") @RequestMapping("/validation/v1/items")
@@ -38,7 +41,35 @@ public class ValidationItemControllerV1 {
} }
@PostMapping("/add") @PostMapping("/add")
public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes) { public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes, Model model) {
// 검증 오류 결과를 보관
Map<String, String> errors = new HashMap<>();
// 검증 로직
if (!StringUtils.hasText(item.getItemName())) {
errors.put("itemName", "상품 이름은 필수입니다.");
}
if (item.getPrice() == null || item.getPrice() < 1000 || item.getPrice() > 1000000) {
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 resultPrice = item.getPrice() * item.getQuantity();
if (resultPrice < 10000) {
errors.put("globalError", "가격 * 수량의 합은 10,000원 이상 이어야 합니다. 현재 값 = " + resultPrice);
}
}
// 검증 실패시
if (!errors.isEmpty()) {
model.addAttribute("errors", errors);
return "validation/v1/addForm";
}
// 검증 성공시
Item savedItem = itemRepository.save(item); Item savedItem = itemRepository.save(item);
redirectAttributes.addAttribute("itemId", savedItem.getId()); redirectAttributes.addAttribute("itemId", savedItem.getId());
redirectAttributes.addAttribute("status", true); redirectAttributes.addAttribute("status", true);

View File

@@ -8,6 +8,10 @@
.container { .container {
max-width: 560px; max-width: 560px;
} }
.field-error {
border-color: #dc3545;
color: #dc3545;
}
</style> </style>
</head> </head>
<body> <body>
@@ -19,17 +23,36 @@
</div> </div>
<form action="item.html" th:action th:object="${item}" method="post"> <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>
<div> <div>
<label for="itemName" th:text="#{label.item.itemName}">상품명</label> <label for="itemName" th:text="#{label.item.itemName}">상품명</label>
<input type="text" id="itemName" th:field="*{itemName}" class="form-control" placeholder="이름을 입력하세요"> <input type="text" id="itemName" th:field="*{itemName}"
th:classappend="${errors?.containsKey('itemName')} ? 'field-error' : _"
class="form-control" placeholder="이름을 입력하세요">
<div class="field-error" th:if="${errors?.containsKey('itemName')}" th:text="${errors['itemName']}">
상품명 오류
</div>
</div> </div>
<div> <div>
<label for="price" th:text="#{label.item.price}">가격</label> <label for="price" th:text="#{label.item.price}">가격</label>
<input type="text" id="price" th:field="*{price}" class="form-control" placeholder="가격을 입력하세요"> <input type="text" id="price" th:field="*{price}"
th:classappend="${errors?.containsKey('price')} ? 'field-error' : _"
class="form-control" placeholder="가격을 입력하세요">
<div class="field-error" th:if="${errors?.containsKey('price')}" th:text="${errors['price']}">
가격 오류
</div>
</div> </div>
<div> <div>
<label for="quantity" th:text="#{label.item.quantity}">수량</label> <label for="quantity" th:text="#{label.item.quantity}">수량</label>
<input type="text" id="quantity" th:field="*{quantity}" class="form-control" placeholder="수량을 입력하세요"> <input type="text" id="quantity" th:field="*{quantity}"
th:classappend="${errors?.containsKey('quantity')} ? 'field-error' : _"
class="form-control" placeholder="수량을 입력하세요">
<div class="field-error" th:if="${errors?.containsKey('quantity')}" th:text="${errors['quantity']}">
수량 오류
</div>
</div> </div>
<hr class="my-4"> <hr class="my-4">