반응형
250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 인프런자바스크립트
- 객체의비교
- Blazor
- 틱택토구현
- 비주얼스튜디오
- HTTP
- sort
- 자바스크립트recude
- 인프런강좌
- 인터넷프로토콜
- 콜백함수
- 자바스크립트틱택토
- 자바스크립트객체리터럴
- 자바스크립트함수
- 이벤트리스너
- 자바스크립트
- slice
- c#
- 객체리터럴
- 자바스크립트파라미터
- 인프런무료강좌
- NPM
- EntityFramework
- 고차함수
- .NET
- 제로초
- 코딩
- 인프런
- 인프런강의
- 인프런인강
Archives
- Today
- Total
샐님은 개발중
[String boot] Bean Validation -오브젝트 오류 본문
스프링 MVC 2편 - 인프런 김영한/섹션 4 ,5- 검증1,2 - Validation
[String boot] Bean Validation -오브젝트 오류
샐님 2023. 7. 13. 19:14728x90
반응형
1. @ScriptAssert 애노테이션 활용
package hello.itemservice.domain.item;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import org.hibernate.validator.constraints.ScriptAssert;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@ScriptAssert(lang ="javascript",script="_this.price * _this.quantity>= 10000", message="총합이 10000원 넘게 입력해주세요.")
public class Item {
private Long id;
@NotBlank
private String itemName;
@NotNull
@Range(min=1000,max=100000)
private Integer price;
@Max(9999)
private Integer quantity;
public Item() {
}
public Item(String itemName, Integer price, Integer quantity) {
this.itemName = itemName;
this.price = price;
this.quantity = quantity;
}
}
2. 자바 코드로 직접 검증 (효율적)
@PostMapping("/add")
public String addItem(@Validated @ModelAttribute Item item , BindingResult bindingResult, RedirectAttributes redirectAttributes) {
//특정 필드 예외가 아닌 전체 예외
if (item.getPrice() != null && item.getQuantity() != null) {
int resultPrice = item.getPrice() * item.getQuantity();
if (resultPrice < 10000) {
bindingResult.reject("totalPriceMin", new Object[]{10000,
resultPrice}, null);
}
}
//검증에 실패하면 다시 입력 폼으로
if (bindingResult.hasErrors()) {
log.info("errors={}",bindingResult);
return "validation/v3/addForm";
}
// 성공 로직
Item savedItem = itemRepository.save(item);
redirectAttributes.addAttribute("itemId", savedItem.getId());
redirectAttributes.addAttribute("status", true);
return "redirect:/validation/v3/items/{itemId}";
}
728x90
반응형
'스프링 MVC 2편 - 인프런 김영한 > 섹션 4 ,5- 검증1,2 - Validation' 카테고리의 다른 글
[Spring boot] Bean Validation - Form 전송 객체 분리 (0) | 2023.07.13 |
---|---|
[String boot] Bean Validation -한계 (0) | 2023.07.13 |
[Spring Boot] Bean Validation (0) | 2023.07.13 |
[Spring-boot] Validator 분리, WebDataBinder (0) | 2023.07.13 |
[Spring-boot] MessageCodesResolver 오류 검증 (0) | 2023.07.13 |