[Spring_Boot] 페이지( 판매 여부/ 등록 지역/ 상품 종류/ 배송 방식)버튼

최현석·2022년 11월 29일
0

Spring_Boot

목록 보기
11/31
post-thumbnail

🧩 th:field

  • th:field="${item.itemName}"
    -> id="itemName" name="itemName" 을 같이 만들어준다.
  • th:field = *{itemName} <-${item.itemName}
    -> th:object 소속이라는 뜻의 *을 넣어주면 item도 생략 가능하다.
    -> th:field : name, id, value 속성을 자동으로 만들어 준다.
    -> label for="itemName" 라벨에 for로 정의되어있다면 id는 사용
    id="itemName" th:field="*{itemName}"

🧩 체크박스

  • 체크박스 체크여부
    open = on&_open=on
    -> open에 값이 있는 것을 확인하고, 사용.
    -> true 결과값을 출력
    -> _open을 무시

  • _open = on
    -> 체크박스를 체크하지 않으면 Spring이 open만 있는 것을 확인하고
    open이 값이 체크되지 않았다고 인식.
    -> 이 경우 서버에서 null이 아니라 false인 것을 확인 할 수 있다.
     

🧩실습

🧩생성자

1) DeliveryCode

@Data
@AllArgsConstructor
public class DeliveryCode {
	
	private String code;
	private String displayName;
}

2) Item

@Getter @Setter
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 deliveryCode;	// 배송 방식
	
	
	
	public Item() {}

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

3) ItemType

public enum ItemType {
	BOOK("도서"),FOOD("식품"), ETC("기타");
	
	private final String description;
	
	private ItemType(String description) {
		this.description = description;
	}
	
	public String getDescription() {
		return description;
	}
	
}


🧩 R, C

1) ItemRepository

	// 수정
	// itemId를 기준으로 updateParam값을 받아온다(수정을 원하는 item값)
	public void update(Long itemId, Item updateParam) {
		// item을 먼저 찾는다.
		Item findItem = findById(itemId);
		findItem.setItemName(updateParam.getItemName());
		findItem.setPrice(updateParam.getPrice());
		findItem.setQuantity(updateParam.getQuantity());
		
		
		findItem.setOpen(updateParam.getOpen()); 		 // 판매 여부
		findItem.setRegions(updateParam.getRegions()); 	 // 등록 지역
		findItem.setItemType(updateParam.getItemType()); // 상품 종류
		findItem.setDeliveryCode(updateParam.getDeliveryCode()); // 배송 방식
	}

2) ItemController

2-1)@ModelAttribute

  • Controller를 호출할 떄 (어떤 메서드가 호출이 되던간에) model에 자동으로 해당 내용이 담기는게 보장된다.
  • @ModelAttribute("regions")regions key값으로 regions value값이 add
	@ModelAttribute("regions")
	public Map<String , String> regions(){
		// LinkedHashMap : 순서가 보장된다.
		Map<String, String> regions = new LinkedHashMap<String, String>();
		regions.put("SEOUL", "서울");
		regions.put("BUSAN", "부산");
		regions.put("JEJU", "제주");
		
		return regions;
	}
	
	@ModelAttribute("itemType")
	public ItemType[] itemTypes() {
		// enum에 있는 값을 배열로 넘겨준다.
		return ItemType.values();
	}
	
	@ModelAttribute("deliveryCodes")
	public List<DeliveryCode> deliveryCodes(){
		List<DeliveryCode> deliveryCodes = new ArrayList<DeliveryCode>();
		deliveryCodes.add(new DeliveryCode("FAST", "빠른배송"));
		deliveryCodes.add(new DeliveryCode("NORMAL", "일반배송"));
		deliveryCodes.add(new DeliveryCode("SLOW", "느린배송"));
		
		return deliveryCodes;
	}
	

    /*------------------------------------------------------*/
    
	@GetMapping("/add")
	public String addForm(Model model) {
		// 타임리프 사용
		// 빈객체를 item이라는 키값에 넘겨준다.
		model.addAttribute("item",new Item());
		
		return "basic/addForm";
	}
    
   	@PostMapping("/add")
	public String saveV6(Item item, RedirectAttributes redirectAttributes){
		
		// 체크박스
		System.out.println("item.open = " + item.getOpen());
		System.out.println("item.regions = " + item.getRegions());
		System.out.println("item.itemType = " + item.getItemType());
		
		Item saveItem = itemRepository.save(item);
		redirectAttributes.addAttribute("itemId", saveItem.getId());
		redirectAttributes.addAttribute("status", true);
		
		return "redirect:/basic/items/{itemId}";
	} 


🧩 Form

1) addForm

  • editForm과 동일

1-1) 멀티 체크박스

  • regions라는 반복가능한 요소를 th:each로 반복하도록 선언한다.

  • th.field 속성을 넣으면 th:value에 들어가는 region.key 값과 비교해 값이 포함되있으면 checked가 추가된다. 즉, 자동으로 value와 비교해서 checked 여부를 설정할 수 있다.

  • th:for="${#ids.prev('regions')}"
    ⇒ 멀티 체크박스는 같은 이름의 여러 체크박스가 생성된다. name 속성은 모두 같아도 되지만 id는 유일해야하기에 모두 달라야 한다. 타임리프에서는 편의목적으로 ids라는 프로퍼티를 제공하며 다음과 같은 메서드도 제공한다. ids는 반복하는 요소의 인덱스로 1,2,3처럼 숫자다.
    ids.prev(...) : 아이디 앞에 인수값을 문자열 결합해준다. (Ex: ids.prev('data')→ data1)
    ids.next(...) : 아이디 뒤에 인수값을 문자열 결합해준다. (Ex: ids.prev('data')→ 1data)


1-2) 라디오 버튼

  • 반복요소의 count만큼 내부 태그가 반복되어 생성된다.

  • th:field에 들어간 th:object에서 선언한 item의 요소는 th:value의 값과 비교해 checked가 자동으로 표현된다.

  • 멀티 체크박스와 동일하게 th:each속성 내부에서 ids를 이용해 인덱스접근및 인수로 넘겨준 값과 문자열 결합으로 고유한 아이디를 만들 수 있다.

  • 라디오버튼은 아무것도 선택하지 않을 경우 아무 값도 넘어가지 않아 Null이 된다


1-3) 셀렉트 박스

  • select 태그에 선언된 th:field 속성과 option에서 선언된 th:value를 타임리프가 비교해 일치할 경우 자동으로 selected 된다.


<h4 class="mb-3">상품 입력</h4>
		<form action="item.html" th:object="${item}" th:action="@{/basic/items/add}" method="post">
			<div>
				<label for="itemName">상품명</label> 
				<input type="text" id="itemName" th:field="*{itemName}"
					class="form-control" placeholder="이름을 입력하세요">
			</div>
			<div>
				<label for="price">가격</label> 
				<input type="text" id="price" th:field="*{price}" 
					class="form-control" placeholder="가격을 입력하세요">
			</div>
			<div>
				<label for="quantity">수량</label> 
				<input type="text" id="quantity" th:field="*{quantity}" 
					class="form-control" placeholder="수량을 입력하세요">
			</div>
	<hr class="my-4">
			<!-- checkbox -->
<!-- 			<div>판매 여부</div> -->
<!-- 			<div> -->
<!-- 				<div class="form-check"> -->
<!-- 					<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> -->
<!-- 				</div> -->
<!-- 			</div> -->

			<!-- checkbox, thymeleaf -->
			<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>
			
			<!-- multi checkbox -->
			<div>
				<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')}"
						 class="form-check-label" th:text="${region.value }">서울</label>
				</div>
			</div>

			<!-- radio button -->
			<div>
				<div>상품 종류</div>
				<div th:each="type : ${itemType}" class="form-check form-check-inline">
					<input type="radio" th:field="*{itemType}" th:value="${type.name}" 
						class="form-check-input">
					<label class="form-check-label" th:for="${#ids.prev('itemType')}"
						 th:text="${type.description}"> </label>
				</div> 
			</div>
			
			<!-- select -->
			<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}">
					</option>					
				</select>
			</div>

2) item

	<hr class="my-4">
		<!-- checkbox, thymeleaf -->
		<div>판매 여부</div>
			<div>
				<div class="form-check">
					<input type="checkbox" id="open" th:field="${item.open}"
						 class="form-check-input" disabled>
					<label for="open" class="form-check-label">판매 오픈</label>
				</div>
			</div>
			
		<!-- multi checkbox -->
		<div>
			<div>등록 지역</div>
			<div th:each="region : ${regions}" class="form-check form-check-inline">
				<input type="checkbox" th:field="${item.regions}" th:value="${region.key}" 
					class="form-check-input" disabled>
				<label th:for="${#ids.prev('regions')}" 
					class="form-check-label" th:text="${region.value }">서울</label>
			</div>
		</div>	
		
		<!--  radio button -->
		<div>
			<div>상품 종류</div>
			<div th:each="type : ${itemType}" class="form-check form-check-inline">
				<input type="radio" th:field="${item.itemType}" th:value="${type.name()}" 
					class="form-check-input" disabled>
				<label class="form-check-label" th:for="${#ids.prev('itemType')}"
					 th:text="${type.description}"></label>
			</div> 
		</div>
	
		<!-- select -->
		<div>
			<div>배송방식</div>
			<select th:field="${item.deliveryCode}" class="form-select" disabled>
				<option value="">=== 배송 방식 선택 ===</option>					
				<option th:each="deliveryCode : ${deliveryCodes}"
					th:value="${deliveryCode.code}" 
					th:text="${deliveryCode.displayName}">
				</option>					
			</select>
		</div>

결과

0개의 댓글