관리 메뉴

웹개발 블로그

[Thymeleaf] 라디오버튼 + 데이터(Enum)으로 보내기 본문

◆Thymeleaf(타임리프)/기초

[Thymeleaf] 라디오버튼 + 데이터(Enum)으로 보내기

쿠키린 2023. 2. 4. 18:32
public enum ItemType {//상품종류는 ENUM을 사용!, 설명은 DeliveryCode 클래스에서

    BOOK("도서"),
    FOOD("음식"),
    ETC("기타");

    private final String description;

    ItemType(String description) {
        this.description = description;
    }

    /*중요!! 꺼내서 사용해야하니까!! 프로퍼티 접근법*/
    public String getDescription() {
        return description;
    }
}

🔼ItemType.java

 

/** 라디오 버튼
 * Enum으로 생성한 데이터를 보낼거당.
 * */
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
    //ItemType[] values = ItemType.values();
    return ItemType.values();//ItemType.values()를 사용하면 해당 ENUM의 모든 정보를 배열로 반환한다.
}

....

🔼Controller.java + @ModelAttribute

 

 

<!-- radio button -->
<div>
    <div>상품 종류</div>
    <div th:each="type : ${itemTypes}" class="form-check form-check-inline">
        <input type="radio" th:field="*{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>

🔼html( field 스펠링 꼭 지키자 ㅠ)

html

 

 

@Data
public class Item {
	private ItemType itemType; //상품 종류(라디오버튼, 라디오는 무조건 단일선택이므로 list로 안함. ENUM으로 보냈으니 반환값도 똑같이 ItemType)

🔼vo(결과를 받을 vo)