[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (4) enum으로 카테고리 추가
2023. 12. 24. 16:44ㆍPratice/CRUD
반응형
💜 enum 정의 및 사용이유+방법 보러가기
이번에는 enum을 활용하여 카테고리를 추가해보려한다.
▪ 카테고리 제작할 때, enum을 사용하는 이유
새로운 카테고리를 추가하거나 기존 카테고리를 변경할 때 코드 변경이 필요한 부분이
Enum 내에 집중되어 있어 유지보수가 용이하기 때문
🟢 CategoryTypeRole
Constant 폴더에 CategoryTypeRole Class 생성
public enum CategoryTypeRole {
ALL("전체"),
FOOD("음식"),
CLOTHES("의류"),
BEAUTY("화장품"),
ETC("기타");
private final String description;
//카테고리의 설명 저장
CategoryTypeRole(String description) {
this.description = description;
}
//설명 가져오기
public String getDescription() {
return description;
}
}
🟢 Entity
@Enumerated(EnumType.STRING)
private CategoryTypeRole categoryTypeRole;
🟢 DTO
@NotNull(message = "카테고리를 선택하세요.")
private CategoryTypeRole categoryTypeRole;
🟢 Controller
상품등록, 수정 부분에 내용 추가
//삽입폼
@GetMapping("/productinsert")
public String insertForm (Model model) throws Exception {
ProductDTO productDTO = new ProductDTO();
model.addAttribute("productDTO", productDTO);
model.addAttribute("categoryTypeRole", CategoryTypeRole.values());
return "/product/insert";
}
//삽입 처리
@PostMapping("/productinsert")
public String insertProc (@Valid ProductDTO productDTO, BindingResult bindingResult, Model model) throws Exception {
if(bindingResult.hasErrors()) {
model.addAttribute("categoryTypeRole", CategoryTypeRole.values());
return "/product/insert";
} productService.insert(productDTO);
return "redirect:/productlist";
}
//수정폼
@GetMapping("/productupdate")
public String updateForm (Integer productId, Model model) throws Exception {
ProductDTO productDTO = productService.findOne(productId);
model.addAttribute("productDTO", productDTO);
model.addAttribute("categoryTypeRole", CategoryTypeRole.values());
return "/product/update";
}
//수정처리
@PostMapping("/productupdate")
public String updateProc (@Valid ProductDTO productDTO, BindingResult bindingResult, Model model) throws Exception {
if(bindingResult.hasErrors()) {
model.addAttribute("categoryTypeRole", CategoryTypeRole.values());
return "/product/update";
} productService.update(productDTO);
return "redirect:/productlist";
}
더보기
categoryTypeRole을 선언하는 이유
해당 폼에서 사용되는 데이터를 초기화하고, 사용자에게 올바른 선택지를 제공
🟢 insert.html
<div class="mb-3 mt-3">
<label for="categoryTypeRole">카테고리</label>
<select class="form-control" id="categoryTypeRole" name="categoryTypeRole" required>
<option th:each="type:${categoryTypeRole}"
th:unless="${type.name() == 'ALL'}"
th:value="${type.name()}"
th:text="${type.getDescription()}"
th:selected="${type.name() eq data?.categoryTypeRole?.name()}">
</option>
</select>
</div>
더보기
ALL 카테고리는 select list에서 제외
getDescription() : 각 카테고리의 설명을 텍스트로 설정
data?.categoryTypeRole?.name()
data가 null인 경우를 대비해 세이프 네비게이션(?.) 연산자를 사용하여 null 체크를 수행
🟢 list.html
<td>
<div th:if="${data.categoryTypeRole != null}">
<div th:utext="${#strings.replace(data.categoryTypeRole.description, '\n', ' ')}"></div>
</div>
</td>
더보기
utext
특정 텍스트를 HTML 엔터티로 변환하지 않고 그대로 출력하게 해 줌
ex) <는 <로, >는 >로 변환되는 것을 막아 줌
description 값에서 개행 문자('\n')를 HTML 엔터티 로 대체
카테고리의 설명에서 개행이 있는 경우에는 해당 위치에 HTML에서 줄 바꿈을 나타내는 엔터티( )가 출력 HTML에서 엔터티 는 줄 바꿈을 의미
🟢 detail.html
<div class="mb-3 mt-3">
<label for="categoryTypeRole" >카테고리</label>
<input type="text" class="form-control" id="categoryTypeRole" name="categoryTypeRole"
th:if="${productDTO.categoryTypeRole != null}"
th:value="${productDTO.categoryTypeRole.getDescription()}" readonly>
<input type="text" class="form-control" id="categoryTypeRole" name="categoryTypeRole"
th:if="${productDTO.categoryTypeRole == null}" value="" readonly>
</div>
🟢 update.html
ALL 카테고리는 select list에서 제외
<div class="mb-3 mt-3">
<label for="categoryTypeRole" >카테고리</label>
<select class="form-control" id="categoryTypeRole" name="categoryTypeRole" required>
<option th:each="type: ${categoryTypeRole}"
th:unless="${type.name() == 'ALL'}"
th:text="${type.getDescription()}"
th:value="${type.name()}"
th:selected="${type.name() eq data?.categoryTypeRole?.name()}">
</option>
</select>
</div>
반응형
'Pratice > CRUD' 카테고리의 다른 글
[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (6) 조회수 증가 기능 (0) | 2024.01.02 |
---|---|
[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (5) 검색 & 페이지 기능 (0) | 2023.12.24 |
[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (3-1) required로 유효성 검사 (0) | 2023.12.24 |
[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (3)검증 오류 추가 (0) | 2023.12.24 |
[Java+SpringBoot+JPA] 기본 CRUD 구현하기 (2)html (0) | 2023.12.23 |