반응형
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
- .orelseThrow
- 김영한
- 유연한 컨트롤러1 - v5
- 필터vs인터셉터
- 세션vs쿠키
- springSecurityFilterChain 오류
- 구글 보안 api 활용
- SpringMVC
- filter vs interceptor
- 쿠키의 정의
- application-properties
- 쿠키란
- spring MVC
- controller
- 세션의 정의
- abap value in field Data Class error
- 세션이란
- n+1
- 인터셉터의 정의
- BindingResult
- java.lang.AssertionError
- 401오류
- MVC
- Validation
- optional
- jpa
- spring
- @Controller
- 필터의 정의
- Testcode
Archives
- Today
- Total
ABAP DUMP ERROR 24시
BindingResult Version3 properties를 활용한 동적 변경 본문
반응형
# 인프런 김영한의 스프링 MVC 2편 - 백엔드 웹 개발 핵심 기술을 개인적으로 정리한 글입니다.
정리
Q. 어떻게 에러 메세지도 properties를 사용해서 동적으로 변경시킬수 있을까?
public FieldError(String objectName, String field, @Nullable Object rejectedValue, boolean bindingFailure, @Nullable String[] codes, @Nullable Object[] arguments, @Nullable String defaultMessage)
codes 와 arguments에
new String[]{"range.item.price"}, new Object[]{1000, 1000000}
code에는 application.properties에 들어갈 설정을 넣고
arguments에서는 0 과 1에 들어갈 내용을 집어 넣으면 된다.
range.item.price=가격은 {0} ~ {1} 까지 허용합니다.
살펴보기
1. application.properties 에 다음과 같이 등록한다.
spring.messages.encoding=UTF-8
spring.messages.basename=messages,errors
2. errors.properties를 생성한후 다음과 같은 내용을 추가한다.
required.item.itemName=상품 이름은 필수입니다.
range.item.price=가격은 {0} ~ {1} 까지 허용합니다.
max.item.quantity=수량은 최대 {0} 까지 허용합니다.
totalPriceMin=가격 * 수량의 합은 {0}원 이상이어야 합니다. 현재 값 = {1}
여기서 0 과 1이란 변수 가 들어갈 순서를 적용시키는 역할을 한다.
3. BindingResult.addError(new FieldError("")) 에 다음처럼 추가한다.
@PostMapping("/add")
public String addItemV3(@ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes){
if(!StringUtils.hasText(item.getItemName())){
bindingResult.addError(new FieldError("item", "itemName", item.getItemName(), false, new String[]{"required.item.itemName"}, null,null));
}
if(item.getPrice() == null || item.getPrice() < 1000 || item.getPrice() > 1000000){
bindingResult.addError(new FieldError("item", "price", item.getPrice(), false, new String[]{"range.item.price"}, new Object[]{1000, 1000000}, null));
}
if(item.getQuantity() == null || item.getQuantity() > 10000){
bindingResult.addError(new FieldError("item" , "quantity", item.getQuantity(),false,new String[]{"max.item.quantity"}, new Object[]{9999}, null));
}
if (item.getPrice() != null && item.getQuantity() != null){
int resultPrice = item.getPrice() * item.getQuantity();
if (resultPrice < 10000){
bindingResult.addError(new ObjectError("item", new String[]{"totalPriceMin"}, new Object[]{10000, resultPrice}, null));
}
}
if (bindingResult.hasErrors()){
log.info("errors={}", bindingResult);
return "validation/v2/addForm";
}
Item savedItem = itemRepository.save(item);
redirectAttributes.addAttribute("itemId", savedItem.getId());
redirectAttributes.addAttribute("status", true);
return "redirect:/validation/v2/items/{itemId}";
}
4. FieldError가 가지고 있는 파라미터의 역할
public FieldError(String objectName, String field, @Nullable Object rejectedValue, boolean bindingFailure, @Nullable String[] codes, @Nullable Object[] arguments, @Nullable String defaultMessage)
다음과 같은 역할을 하는데
우리가 만든 properties의 역할을 하기 위해서는
@Nullable String[] codes, @Nullable Object[] arguments
부분에 집중해야한다.
반응형
'[WEB]Back-end > Spring MVC' 카테고리의 다른 글
Validator interface 활용하기 (0) | 2022.02.22 |
---|---|
BindingResult , add FieldError=-> rejectValue 변환 (0) | 2022.02.21 |
BindingResult를 활용한 Validation 처리 [전 vs 후(version1,2) ] (0) | 2022.02.19 |
Thylmleaf 간단 용어 정리 (0) | 2022.02.18 |
HTTP 메시지 컨버터가 뭐야? (0) | 2022.02.16 |
Comments