타임리프 체크박스
- enum을 사용해서 상품 종류를 선택하는 간단한 로직을 짜 볼 것이다
- 첫 번째로 상품 종류를 담고 있는 enum이 필요하다
public enum ItemType{
BOOK("도서"), FOOD("음식"), ETC("기타");
private final String description;
ItemType(String descrption) {
this.description = description;
}
}
- 두 번째로 상품에 대한 정보에 대한 프로퍼티가 필요하다
@Data
public class Item {
private Long id;
private String itemName;
private Integer price;
private Integer quantity;
private ItemType itemType;
public Item() {
}
public Item(String itemName, Integer price, Integer quantity){
this.itemName = itemName;
this.price = price;
this.quantity = quantity;
}
}
- 그리고 뷰에 연결하기 위해서 ModelAttribute를 사용해서 반환한 값이 자동으로 모델에 저장된다
- ENUM을 사용해서 [BOOK, FOOD, ETC]를 반환한다
@ModelAttribute("itemTypes")
public ItemType[] itemTypes(){
return ItemType.values();
}
- HTML에 THYMELEAF를 사용해서 값을 넣어줄 것이다
<!-- radio button -->
<div>
<div>상품 종류</div>
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
<input type="radio" th:field="${item.itemType}" th:value="${type.name()}"
class="form-check-input">
<label th:for="${#ids.prev('itemType')}" th:text="${type.description}"
class="form-check-label">
BOOK
</label>
</div>
</div>
- th:each문은 반복문이다 enum에 있는 속성들이 하나씩 들어가게 된다
- type은 라디오 타입이고 th:field를 사용해서 id, name, checked을 부여해준다
- th:for=”$ids.prev(’regions’)는 id에 숫자를 붙여 모두 다른 id값을 지원해준다
댓글