Spring/Spring MVC
Spring MVC - 타임리프(Thymeleaf)을 사용한 Radio button(라디오 버튼)
jddng
2022. 2. 4. 16:39
728x90
반응형
타임리프(Thymeleaf)을 사용한 Radio button(라디오 버튼)
라디오 버튼은 여러 선택지 중에 하나를 선택할 때 사용할 수 있다. 자바 Enum을 활용해서 라디오 버튼을 사용해 보자
public enum ItemType {
BOOK("도서"), FOOD("식품"), ETC("기타");
private final String description;
ItemType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
- Radio Button을 설명하기위해 생성한 Enum 클래스
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
return ItemType.values();
}
- Enum 클래스를 타임리프에서 사용하기위해 컨트롤러에 코드 추가
- 컨트롤이 호출할 때마다 자동으로 실행되어 Model에 return 된 객체를 담아준다.
- ItemType.values() 를 사용하면 Enum의 모든 정보를 배열로 반환한다. [BOOK, FOOD, ETC]
- Radio Button를 설명하기 위한 작성한 코드로 좋은 방법은 아니다
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
- th:each 를 이용하여 enum의 개수만큼 radio를 생성
<input type="radio" th:field="*{itemType}" th:value="${type.name()}" class="form-check-input">
- id는 유일값이어야 한다. 자동으로 반복문이 실행될 때마다
id="itemType1", id="itemType2", id="itemType3"으로 추가해준다 - ${type.name()}은 Enum의 name을 그대로 가져온다.(Enum 클래스 기능) "BOOK", "FOOD", "ETC"
- *{itemType} = ${item.itemType}
<label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label">BOOK</label>
- radio의 id는 타임리프에 의해 동적으로 만들어지기 때문에 타임리프에서 제공되는
ids.prev(...) , ids.next(...)를 이용한다. (동적으로 생성된 id값을 가져올 수 있다) - th:text="${type.description}" : "도서", "식품", "기타" 값 출력
전체 코드
<!-- 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의 소스 코드를 보면 다음과 같다.
<!-- radio button -->
<div>
<div>상품 종류</div>
<div class="form-check form-check-inline">
<input type="radio" value="BOOK"
class="form-check-input" id="itemType1" name="itemType">
<label for="itemType1" class="form-check-label">도서</label>
</div>
<div class="form-check form-check-inline">
<input type="radio" value="FOOD"
class="form-check-input" id="itemType2" name="itemType">
<label for="itemType2" class="form-check-label">식품</label>
</div>
<div class="form-check form-check-inline">
<input type="radio" value="ETC"
class="form-check-input" id="itemType3" name="itemType">
<label for="itemType3" class="form-check-label">기타</label>
</div>
</div>
728x90
반응형