publicenumItemType{BOOK("도서"),FOOD("식품"),ETC("기타");privatefinalStringdescription;ItemType(Stringdescription){this.description=description;}publicStringgetDescription(){returndescription;}}@Data@AllArgsConstructorpublicclassDeliveryCode{privateStringcode;privateStringdisplayName;}@DatapublicclassItem{privateLongid;privateStringitemName;privateIntegerprice;privateIntegerquantity;privateBooleanopen;// 판매 여부privateList<String>regions;// 등록 지역privateItemTypeitemType;// 상품 종류privateStringdeliveryCode;// 배송 방식 publicItem(){}publicItem(StringitemName,Integerprice,Integerquantity){this.itemName=itemName;this.price=price;this.quantity=quantity;}}
single checkbox
1
2
3
4
5
6
7
8
<!-- added single checkbox --><div>판매 여부</div><div><divclass="form-check"><inputtype="checkbox"id="open"th:field="*{open}"class="form-check-input"><labelfor="open"class="form-check-label">판매 오픈</label></div></div>
1
2
3
4
5
@PostMapping("/add")publicStringaddItemV6(Itemitem,RedirectAttributesredirectAttributes){log.info("item open = {}",item.getOpen());...}
checked: true, unchecked: false 체크박스 체크시 html form 에서 open=on 이라는 값으로 넘어오고 스프링은 on 이라는 문자를 true 타입으로 변환(스프링 타입 컨버터가 수행한다.) 체크박스 선택하지 않고 폼 전송시, open 이라는 피드 자체가 서버로 전송되지 않는다. 이는 값을 수정할 경우 문제를 야기한다.
1
2
3
4
5
6
7
8
9
10
11
12
<!-- 타임리프가 아닐 경우 히든 필드 속성(_open) 추가 --><divclass="form-check"><inputtype="hidden"name="_open"value="on"/><inputtype="checkbox"id="open"name="open"class="form-check-input"><labelfor="open"class="form-check-label">판매 오픈</label></div><!-- 타일 리프 사용할 경우 --><divclass="form-check"><inputtype="checkbox"id="open"th:field="*{open}"class="form-check-input"><labelfor="open"class="form-check-label">판매 오픈</label></div>
th:field="*{open}" _open=on 속성을 항상 전송 값이 true면, 체크를 자동으로 처리(checked=”checked”)
multi checkbox
1
2
3
4
5
6
7
8
9
// Controller 내 @ModelAttribute("regionsA")publicMap<String,String>regions(){LinkedHashMap<String,String>regionsB=newLinkedHashMap<>();regionsB.put("SEOUL","서울");regionsB.put("BUSAN","부산");regionsB.put("JEJU","제주");returnregionsB;}
컨트롤러 내 모든 메소드 호출 시 데이터(regionB)가 담겨져 있다. == model.addAttribute(“regionsA”, regionsB);
<!-- 코드 --><div><div>등록 지역</div><divth:each="region : ${regionsA}"class="form-check form-check-inline"><inputtype="checkbox"th:field="*{regions}"th:value="${region.key}"class="form-check-input"><labelth:for="${#ids.prev('regions')}"th:text="${region.value}"class="form-check-label">서울</label></div></div><!-- 렌더링 된 html --><div><div>등록 지역</div><divclass="form-check form-check-inline"><inputtype="checkbox"value="SEOUL"class="form-check-input"id="regions1"name="regions"><inputtype="hidden"name="_regions"value="on"/><labelfor="regions1"class="form-check-label">서울</label></div><divclass="form-check form-check-inline"><inputtype="checkbox"value="BUSAN"class="form-check-input"id="regions2"name="regions"><inputtype="hidden"name="_regions"value="on"/><labelfor="regions2"class="form-check-label">부산</label></div><divclass="form-check form-check-inline"><inputtype="checkbox"value="JEJU"class="form-check-input"id="regions3"name="regions"><inputtype="hidden"name="_regions"value="on"/><labelfor="regions3"class="form-check-label">제주</label></div></div>
th:each: 체크박스가 반복 생성될 때 id 뒤에 숫자 추가 th:for="${#id.prev('regions')}": 숫자가 붙은 새로 생성된 id 값을 사용 선택된 값을 서버에서 List로 받는다.
<div><div>상품 종류</div><divth:each="itemType : ${itemTypes}"class="form-check form-check-inline"><inputtype="radio"th:field="*{itemType}"th:value="${itemType.name()}"class="form-check-input"><labelth:for="${#ids.prev('itemType')}"th:text="${itemType.description}"class="form-check-label"></label></div></div><!--
타임리프테서 ENUM 직접 접근
ENUM의 패키지 위치가 변경될 경우
--><divth:each="type : ${T(hello.itemservice.domain.item.ItemType).values()}">
<div><div>배송 방식</div><selectth:field="*{deliveryCode}"class="form-select"><optionvalue="">==배송 방식 선택==</option><optionth:each="deliveryCode:${deliveryCodes}"th:value="${deliveryCode.code}"th:text="${deliveryCode.displayName}">test</option></select></div>
errors?. errors 가 null 일 경우, NullPointerException 발생 x errors 가 null 일 경우, null 반환 th:if 에서 null 은 실패로 처리되므로 오류 메시지가 출력되지 않는다. classappend 를 사용해서 해당 필드에 오류가 있으면 field-error 라는 클래스 정보를 더해서 폼의 색깔을 빨간 색으로 강조한다. 만약 값이 없으면 _ (No-Operation)을 사용해서 아무것도 하지 않는다.