입력 폼 처리

th:object : 커맨드 객체를 지정한다.

*{...} : 선택 변수 식이라고 한다. th:object 에서 선택한 객체에 접근한다.

th:field

HTML 태그의 id , name , value 속성을 자동으로 처리해준다.

<form action="item.html" th:action th:object="${item}" method="post">
 <div>
	 <label for="itemName">상품명</label>
	 <input type="text" id="itemName" th:field="*{itemName}" class="formcontrol" placeholder="이름을 입력하세요">
 </div>

체크 박스 - 단일1

HTML에서 체크 박스를 선택하지 않고 폼을 전송하면 open 이라는 필드 자체가 서버로 전송되지 않는다.

<input type="checkbox" id="open" name="open" class="form-check-input">
<input type="hidden" name="_open" value="on"/> <!-- 히든 필드 추가 -->
<label for="open" class="form-check-label">판매 오픈</label>

체크 박스를 체크하지 않으면 스프링 MVC가 _open 만 있는 것을 확인하고, open 의 값이 체크되지 않았다고 인식한다.

이 경우 서버에서 Boolean 타입을 찍어보면 결과가 null 이 아니라 false 인 것을 확인할 수 있다.

체크 박스 - 단일2

<input type="checkbox" id="open" th:field="*{open}" class="form-checkinput"> 
->
<input type="checkbox" id="open" class="form-check-input" name="open" value="true">
**<input type="hidden" name="_open" value="on"/>**

타임리프를 사용하면 체크 박스의 히든 필드와 관련된 부분도 함께 해결해준다. HTML 생성 결과를 보면 히든 필드 부분이 자동으로 생성되어 있다.

<input type="checkbox" id="open" th:field="${item.open}" class="formcheck-input" disabled>
->
<input type="checkbox" id="open" class="form-check-input" disabled
name="open" value="true" **checked="checked"**>

체크 박스에서 판매 여부를 선택해서 저장하면, 조회시에 checked 속성이 추가된 것을 확인할 수 있다.

체크 박스 - 멀티

<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>

#ids.

name 은 같아도 되지만, id 는 모두 달라야 해서 타임리프는 체크박스를 each 루프 안에서 반복해서 만들 때 임의로 1 , 2 , 3 숫자를 뒤에 붙여준다.

라디오 버튼

체크박스와 유사

ENUM 사용

ItemType.values() 를 사용하면 해당 ENUM의 모든 정보를 배열로 반환한다. 예) [BOOK, FOOD, ETC]

셀렉트 박스

<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>
->
<select class="form-select" id="deliveryCode" name="deliveryCode">
 <option value="">==배송 방식 선택==</option>
 <option value="FAST">빠른 배송</option>
 <option value="NORMAL">일반 배송</option> <option value="SLOW">느린 배송</option>
</select>