⚙️ 개발/Spring

[Tymeleaf] 체크 박스, 셀렉트 박스

지구용사 2024. 5. 2. 10:14

타임리프를 사용해서 폼에서 체크박스, 라디오 버튼, 셀렉트 박스를 편하게 사용할 수 있다.

 

 

상품 종류 ENUM으로 생성

public enum ItemType {
    BOOK("도서"),
    FOOD("음식"),
    ETC("기타");

    private final String description;

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

 

배송방식 클래스 생성

/**
 * FAST 빠른 배송
 * NORMAL 일반 배송
 * SLOW 느린 배송
 */
@Data
@AllArgsConstructor
public class DeliveryCode {
    private String code;
    private String displayName;
}

 

상품 객체 수정

@Data
public class Item {

    private Long id;
    private String itemName;
    private Integer price;
    private Integer quantity;
    
    private Boolean open; //판매 여부
    private List<String> regions; //등록 지역
    private ItemType itemType; //상품 종류
    private String deliverCode; //배송 방식

    public Item() {
    }

    public Item(String itemName, Integer price, Integer quantity) {
        this.itemName = itemName;
        this.price = price;
        this.quantity = quantity;
    }
}

 


단일 체크 박스

 

체크박스를 체크하면 HTML Form에 open=on이라는 값이 넘어간다.

스프링은 on이라는 문자를 true타입으로 변환해준다.

<div>판매 여부</div>
<div>
    <div class="form-check">
        <input type="checkbox" id="open" name="open" class="form-check-input">
        <label for="open" class="form-check-label">판매 오픈</label>
    </div>
</div>

 

선택하지 않고 보낼 경우 open이라는 필드 자체가 전송되지 않아 null이다.

그래서 스프링MVC는 오류를 고려하여 _open와 같은 히든 필트를 만들어 체크 해제를 판단한다.

<input type="hidden" name="_open" value="on"/>

 

개발할 때마다 히든 필드를 추가하는 것은 버거로워 타임리프가 이 부분을 자동으로 처리해준다.

<div>판매 여부</div>
<div>
    <div class="form-check">
        <input type="checkbox" id="open" th:field="*{open}" class="form-check-input">
        <label for="open" class="form-check-label">판매 오픈</label>
    </div>
</div>

 


체크박스 멀티

 

@ModelAttribute를 사용하여 반복적으로 사용해야할 코드를 작성한다.

@ModelAttribute("regions")
public Map<String, String> regions() {
    LinkedHashMap<String, String> regions = new LinkedHashMap<>();
    regions.put("SEOUL", "서울");
    regions.put("BUSAN", "부산");
    regions.put("JEJU", "제주");
    return regions;
}
<div>등록 지역</div>
<div th:each="region : ${regions}" class="form-check form-check-inline">
    <input type="checkbox" th:field="*{regions}" th:value="${region.key}" class="form-check-input">
    <label th:for="${#ids.prev('regions')}" th:text="${region.value}" class="form-check-label">서울</label>
</div>
<div>등록 지역</div>
<div class="form-check form-check-inline">
    <input type="checkbox" value="SEOUL" class="form-check-input" id="regions1" name="regions">
    <input type="hidden" name="_regions" value="on"/>
    <label for="regions1"class="form-check-label">서울</label>
</div>
<div class="form-check form-check-inline">
    <input type="checkbox" value="BUSAN" class="form-check-input" id="regions2" name="regions">
    <input type="hidden" name="_regions" value="on"/>
    <label for="regions2" class="form-check-label">부산</label>
</div>
<div class="form-check form-check-inline">
    <input type="checkbox" value="JEJU" class="form-check-input" id="regions3" name="regions">
    <input type="hidden" name="_regions" value="on"/>
    <label for="regions3" class="form-check-label">제주</label>
</div>

 


셀렉트 박스

 

<div>배송 방식</div>
<select th:field="*{deliveryCode}" class="form-select">
    <option value="">==배송 방식 선택==</option>
    <option th:each="deliveryCode : ${deliveryCodes}" th:value="${deliveryCode.code}" th:text="${deliveryCode.displayName}">FAST</option>
</select>
<DIV>배송 방식</DIV>
<select class="form-select" id="deliveryCode" name="deliveryCode">
    <option value="">==배송 방식 선택==</option>
    <option value="FAST">빠른 배송</option>
    <option value="NORMAL">일반 배송</option>
    <option value="SLOW">느린 배송</option>
</select>

 


 

🔗강의 링크

https://inf.run/GMo43