[인프런/스프링 MVC 2편] 2. 타임리프 - 스프링 통합과 폼
타임리프 스프링 통합
스프링 통합으로 추가되는 기능들
- 스프링의 SpringEL 문법 통합
- ${@myBean.doSomething()} 처럼 스프링 빈 호출 지원
- 편리한 폼 관리를 위한 추가 속성
- th:object (기능 강화, 폼 커맨드 객체 선택)
- th:field, th:errors, th:errorclass
- 폼 컴포넌트 기능
- checkbox, radio button, List 등을 편리하게 사용할 수 있는 기능 지원
- 스프링의 메시지, 국제화 기능의 편리한 통합
- 스프링의 검증, 오류 처리 통합
- 스프링의 변환 서비스 통합 (ConversionService)
1. 입력 폼 처리
- th:object : 커맨트 객체 지정
- * { ... } : 선택 변수 식 (th:object에서 선택한 객체에 접근)
- th:field : HTML 태그의 id, name, value 속성을 자동으로 처리
1) 등록 폼
* Controller
비어있는 Item 객체를 뷰로 넘겨줌
@GetMapping("/add")
public String addForm(Model model) {
model.addAttribute("item", new Item());
return "form/addForm";
}
* addForm.html
<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="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>
(1) th:object
<form action="item.html" th:action th:object="${item}" method="post">
- <form>에서 사용할 객체 지정 (컨트롤러에서 넘겨준 item 객체)
(2) th:field = " *{itemName} "
<input type="text" id="itemName" th:field="*{itemName}" class="formcontrol" placeholder="이름을 입력하세요">
- th:field : id, name, value 속성을 모두 자동으로 추가 (th:field에서 지정한 item 객체의 변수 이름, 변수 값 사용)
- *{itemName} : 선택변수식 ( = ${item.itemName} )
* 렌더링 후
- id, name, value 를 모두 자동으로 만들어줌
( item 객체가 비어있으니까 value = "" )
2) 수정 폼
* Controller
@GetMapping("/{itemId}/edit")
public String editForm(@PathVariable Long itemId, Model model) {
Item item = itemRepository.findById(itemId);
model.addAttribute("item", item);
return "form/editForm";
}
* editForm.html
<form action="item.html" th:action th:object="${item}" method="post">
<div>
<label for="id">상품 ID</label>
<input type="text" id="id" class="form-control" th:field="*{id}" readonly>
</div>
<div>
<label for="itemName">상품명</label>
<input type="text" id="itemName" class="form-control" th:field="*{itemName}">
</div>
<div>
<label for="price">가격</label>
<input type="text" id="price" class="form-control" th:field="*{price}">
</div>
<div>
<label for="quantity">수량</label>
<input type="text" id="quantity" class="form-control" th:field="*{quantity}">
</div>
원래 id, name, value를 모두 입력했어야 했는데, 입력 안해도 th:field 덕분에 자동으로 처리됨
* 렌더링 후
- id, name, value 값을 자동으로 만들어줌
2. 요구사항 추가
타임리프를 사용해서 폼에서 체크박스, 라디오버튼, 셀렉트박스를 편리하게 사용하는 방법
기존 상품 서비스에 다음 요구사항 추가
- 판매 여부 (booelan open)
- 판매 오픈 여부
- 단일 체크박스로 선택
- 등록 지역 (List<String> regions)
- 서울, 부산, 제주
- 다중 체크박스로 선택
- 상품 종류 (ItemType itemType)
- 도서, 상품, 기타
- 단일 라디오버튼으로 선택
- 배송 방식 (String deliveryCode)
- 빠른배송, 일반배송, 느린배송
- 단일 셀렉트박스로 선택
1) 객체 만들기
* 상품 종류 - ItemType (Enum)
package hello.itemservice.domain.item;
public enum ItemType {
// 상품 종류
BOOK("도서"), FOOD("음식"), ETC("기타");
// 상품 설명
private final String description;
ItemType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
* 배송 방식 - DeliveryCode
package hello.itemservice.domain.item;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* FAST: 빠른 배송
* NORMAL: 일반 배송
* SLOW: 느린 배송
*/
@Data
@AllArgsConstructor
public class DeliveryCode {
private String code; // FAST, NORMAL, SLOW : 시스템에서 전달하는 값
private String displayName; // 빠른배송, 일반배송, 느린배송 : 고객에게 보여주는 값
}
2) 상품 객체에 변수 추가
*Item - 상품
package hello.itemservice.domain.item;
import lombok.Data;
import java.util.List;
@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 deliveryCode; // 배송 방식
public Item() {
}
public Item(String itemName, Integer price, Integer quantity) {
this.itemName = itemName;
this.price = price;
this.quantity = quantity;
}
}
3. 단일 체크박스 - 단순 HTML 체크박스 사용
1) 히든필드 사용 X
* addForm.html 에 판매여부 div 추가
<!-- single checkbox -->
<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>
* Controller에 로그 추가
// @Slf4j 추가
@Slf4j
...
public class FormItemController {
...
@PostMapping("/add")
public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes) {
// 로그 추가
log.info("item.open={}", item.getOpen());
Item savedItem = itemRepository.save(item);
redirectAttributes.addAttribute("itemId", savedItem.getId());
redirectAttributes.addAttribute("status", true);
return "redirect:/form/items/{itemId}";
}
}
(1) 판매여부 체크했을 때
- 넘어가는 값
* 스프링이 on이라는 문자를 true 타입으로 변환해줌 (스프링 타입 컨버터)
- 로그 결과
(2) 판매여부 체크 안했을 때 (주의)
- 넘어가는 값
- 로그 결과
-> open의 이름 전송 X , 로그 boolean 결과 = null
HTML 체크박스는 선택이 안되면 서버로 값 자체를 보내지 X
-> 수정할 때 문제 생길 수 있음
( 등록할 때는 체크해서 open = on 이었는데, 수정할 때는 체크 안한다면 open 값도 안넘어오니까 수정X )
--> 히든 필드 사용 (약간 트릭)
2) 히든필드 사용
* 히든필드 추가
<!-- single 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>
기존 체크박스 이름 앞에 _를 붙여서 전송
-> 체크한 경우 open도 전송 O, _open도 전송 O
-> 체크 해제한 경우 open은 전송 X, _open만 전송 O
-> 스프링 MVC는 체크를 해제했다고 판단
(1) 체크했을 때
- 넘어가는 값
- 로그 결과
(2) 체크 안했을 때
- 넘어가는 값
- 로그 결과
스프링 MVC가 _open만 있는 것을 확인하고, open의 값이 체크되지 않았다고 인식
null 이 아니라 false로 출력
-> 근데 일일이 히든필드 추가하기 번거로움
-> 타임리프 사용
4. 단일 체크박스 - 타임리프 사용
* 타임리프 체크박스 코드로 변경
1) 상품 등록 폼
* addForm.html
- name 대신 th:field="*{open}" 넣어줌
<!-- single checkbox -->
<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>
* 렌더링 결과
- hidden 필드 자동 추가
* 실행 로그
2) 상품 상세
*item.html
- 주의 : item.html에는 th:object 사용 안했기 때문에 th:field="${item.open}"으로 적어야 함 !
<!-- single checkbox -->
<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>
* 렌더링 결과
- 타임리프의 th:field 사용 -> 넘어온 객체의 체크박스 값이 true인 경우 자동 checked 처리 !
3) 상품 수정
* editForm.html
<!-- single checkbox -->
<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>
체크 박스를 수정해도 반영되지 않음 -> ItemRepository - update() 코드 수정
* Controller의 수정 처리 코드
@PostMapping("/{itemId}/edit")
public String edit(@PathVariable Long itemId, @ModelAttribute Item item) {
itemRepository.update(itemId, item);
return "redirect:/form/items/{itemId}";
}
* ItemRepository - update() 코드
public void update(Long itemId, Item updateParam) {
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());
}
5. 다중 체크 박스
- 등록 지역 : 서울, 부산, 제주 (다중 선택)
1) 상품 등록 폼
* Controller
@ModelAttribute("regions")
public Map<String, String> regions() {
Map<String, String> regions = new LinkedHashMap<>(); // 순서대로 담김
regions.put("SEOUL", "서울");
regions.put("BUSAN", "부산");
regions.put("JEJU", "제주");
return regions;
}
📌 @ModelAttribute의 또다른 사용법
등록 폼, 상세화면, 수정 폼에서 모두 다중 체크박스를 반복해서 보여줘야 함
-> 각 컨트롤러에서 model.addAttribute(...) 를 사용해서 체크박스를 구성하는 데이터를 반복해서 넣어야 함
-> 별도의 메소드에 @ModelAttribute 적용
-> 컨트롤러 내 어떤 메소드를 호출하든 model 안에 regions 값이 담김
-> model.addAttribute("regions", regions);
✔ 참고 : @ModelAttribute가 있는 메소드는 컨트롤러가 호출될 때마다 사용 -> 객체도 계속 생성
-> 미리 static 같은 걸로 생성해두고 재사용 하는 것이 효율적임 !
* addForm.html
<!-- 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')}"
th:text="${region.value}" class="form-check-label">서울</label>
</div>
</div>
(1) th:each="region : ${regions}"
- 다중 체크박스 반복 출력
- model에 "regions"라고 담긴 것을 반복 출력
(2) th:field="*{regions}"
- item 객체의 regions 변수의 이름, 값
(3) th:for="${#ids.prev('regions')}"
- each를 돌릴 때 id 값이 다 달라야 함
- 타임리프는 체크박스를 each 안에서 반복해서 만들 때 임의로 1, 2, 3 숫자를 뒤에 붙여줌
* 렌더링 결과
- model에 담긴 regions 값들을 each 를 통해 체크박스로 반복 출력
- 히든필드 생성
- id 값 지정
* 로그 출력
- 서울 부산 선택
- 지역 선택 X -> 빈 배열 <- 히든필드 때문
(체크를 하나도 안했을 때 아무 데이터를 보내지 않는 것 방지)
2) 상품 상세
* item.html
- 주의 : item.html에는 th:object 사용 X -> th:field에 ${item.regions} 라고 넣어야 함
<!-- 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')}"
th:text="${region.value}" class="form-check-label">서울</label>
</div>
</div>
* 렌더링 결과
- th:value의 값이 "SEOUL" -> th:field(등록 후 넘어온 item 객체의 regions변수)에 서울이 있나 확인 -> 있으면 -> checked 자동 처리
3) 상품 수정
* editForm.html
<!-- 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')}"
th:text="${region.value}" class="form-check-label">서울</label>
</div>
</div>
6. 라디오 버튼
- 상품 종류 : 도서, 식품, 기타 (하나만 선택)
* 상품 종류 - ItemType (ENUM)
package hello.itemservice.domain.item;
public enum ItemType {
// 상품 종류
BOOK("도서"), FOOD("음식"), ETC("기타");
// 상품 설명
private final String description;
ItemType(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
1) 상품 등록
* Controller
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
return ItemType.values(); // enum의 정보들을 배열로 반환
}
- @ModelAttribute
- 등록, 조회, 수정 폼에서 모두 itemTypes 사용
- ItemType.values() : ENUM의 모든 정보를 배열로 반환 [BOOK, FOOD, ETC]
* addForm.html
<!-- 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>
- th:value="${type.name()}" : ENUM의 이름(종류) 반환
* 렌더링 결과
* 로그 출력
- 체크 안할 때 null : 라디오 버튼은 항상 하나를 선택하도록 되어 있으므로 수정 시에도 반드시 선택 -> 수정 시 null 넘어갈 일 X -> 히든필드 사용할 필요 X
2) 상품 상세
* item.html
- th:field="${item.itemType}" 주의
<!-- radio button -->
<div>
<div>상품 종류</div>
<div th:each="type : ${itemTypes}" class="form-check form-check-inline">
<input type="radio" th:field="${item.itemType}" th:value="${type.name()}" class="form-check-input" disabled>
<label th:for="${#ids.prev('itemType')}" th:text="${type.description}" class="form-check-label">
BOOK
</label>
</div>
</div>
* 렌더링 결과
3) 상품 수정
* editForm.html
<!-- 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>
* 타임리프에서 ENUM 직접 사용하기 (비추)
@ModelAttribute로 model에 ENUM 담아서 전달하는 대신
타임리프는 ENUM에 직접 접근 가능
스프링 EL 문법 -> ENUM의 모든 정보가 배열로 반환
<div th:each="type : ${T(hello.itemservice.domain.item.ItemType).values()}">
7. 셀렉트 박스
- 배송방식 : 빠른배송, 일반배송, 느린배송 (하나만 선택)
* 배송 방식 - DeliveryCode
package hello.itemservice.domain.item;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* FAST: 빠른 배송
* NORMAL: 일반 배송
* SLOW: 느린 배송
*/
@Data
@AllArgsConstructor
public class DeliveryCode {
private String code;
private String displayName;
}
1) 상품 등록
* Controller
@ModelAttribute("deliveryCodes")
public List<DeliveryCode> deliveryCodes() {
List<DeliveryCode> deliveryCodes = new ArrayList<>();
deliveryCodes.add(new DeliveryCode("FAST", "빠른 배송"));
deliveryCodes.add(new DeliveryCode("NORMAL", "일반 배송"));
deliveryCodes.add(new DeliveryCode("SLOW", "느린 배송"));
return deliveryCodes;
}
* addForm.html
<!-- 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}">FAST</option>
</select>
</div>
<hr class="my-4">
* 렌더링 결과
2) 상품 상세
* item.html
<!-- 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}">FAST</option>
</select>
</div>
<hr class="my-4">
* 렌더링 결과
- th:field에 들어온 값과 th:value의 값이 같으면 타임리프가 자동으로 selected 처리 !
3) 상품 수정
* editForm.html
<!-- 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}">FAST</option>
</select>
</div>
<hr class="my-4">