티스토리 뷰
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-validation'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
implementation 'org.springframework.boot:spring-boot-starter-validation' 추가
package hello.itemservice.domain.item;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import org.springframework.stereotype.Service;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
@Data
@Service
public class Item {
private Long id;
@NotBlank(message = "공백x")
private String itemName;
@NotNull
@Range(min = 1000, max = 1000000)
private Integer price;
@NotNull
@Max(9999)
private Integer quantity;
public Item() {
}
public Item(String itemName, Integer price, Integer quantity) {
this.itemName = itemName;
this.price = price;
this.quantity = quantity;
}
}
domain에 어노테이션 추가
@PostMapping("/add") // WebDataBinder를 사용하기 위해서는 모델 앞에 @Validated 어노테이션을 추가해야한다.
public String addItemV6(@Validated @ModelAttribute Item item, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
//WebDataBinder로 인해 검증 데이터가 BindingResult에 알아서 쌓이게 된다.
//타입 검증
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}";
}
불러오는 Object(Item) 앞에 @Validated 추가해준다.
'dev_공부일지 > spring boot + intelliJ' 카테고리의 다른 글
bean validation, scriptAssert 사용 (0) | 2023.05.19 |
---|---|
bean validation 사용 시 에러코드 정의 (0) | 2023.05.18 |
검증 Validator 사용 2 @InitBinder 사용 WebDataBinder (0) | 2023.05.16 |
검증 Validator 인터페이스 사용 (0) | 2023.05.16 |
BindingResult 타입오류 일 경우 (0) | 2023.05.15 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 백엔드 개발자 역량
- React
- 로그인
- 스프링공부
- exception
- 항해플러스
- JPA
- 예외처리
- react실행
- Java
- reject
- BindingResult
- 향해99
- 향해플러스백엔드
- 인터셉터
- 리터럴
- 스프링부트
- 항해99
- ArgumentResolver
- SpringBoot
- 백엔드 개발자 공부
- filter
- rejectValue
- thymleaf
- 향해플러스
- hypertexttransferprotocol
- 컨트
- HTTP
- Intercepter
- jpa api
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함