김영한님의 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 강의 내용을 정리한 것입니다.
입력 폼 처리
- th:object : 커맨드 객체를 지정한다.
- *{...} : 선택 변수식이라고 한다. th:object 에서 선택한 객체에 접근한다. → 쉽게 말해서 object에 소속된 것으로 인정된다!
- th:field : HTML 태그의 id , name , value 속성을 자동으로 처리해준다.
렌더링 전
<input type="text" th:field="*{itemName}" />
렌더링 후
<input type="text" id="itemName" name="itemName" th:value="*{itemName}" />
등록 폼
th:object를 적용하려면 해당 오브젝트 정보를 먼저 넘겨주어야 한다.
[FormItemController]
@GetMapping("/add")
public String addForm(Model model) {
model.addAttribute("item", new Item());
return "form/addForm";
}
[form/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>
- th:object="${item}" : <form>에서 사용할 객체를 지정한다. 선택 변수 식( *{...} )을 적용할 수 있다.
- th:field="*{itemName}"
- *{itemName}는 선택 변수 식을 사용했는데, ${item.itemName}과 같다. 앞서 th:object로 item을 선택했기 때문에 선택 변수식을 적용할 수 있다.
- th:field는 id , name , value 속성을 모두 자동으로 만들어준다.
id : th:field에서 지정한 변수 이름과 같다. id="itemName"
name : th:field에서 지정한 변수 이름과 같다. name="itemName"
value : th:field에서 지정한 변수의 값을 사용한다. value=""
* 참고
id 속성을 제거해도 th:field가 자동으로 생성해준다.
렌더링 전
<input type="text" id="itemName" th:field="*{itemName}" class="form-control" placeholder="이름을 입력하세요">
렌더링 후
<input type="text" id="itemName" class="form-control" placeholder="이름을 입력하세요" name="itemName" value="">
수정 폼
[FormItemController]
@GetMapping("/{itemId}/edit")
public String editForm(@PathVariable Long itemId, Model model) {
Item item = itemRepository.findById(itemId);
model.addAttribute("item", item);
return "form/editForm";
}
[form/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>
렌더링 전
<input type="text" id="itemName" th:field="*{itemName}" class="form-control">
렌더링 후
<input type="text" id="itemName" class="form-control" name="itemName" value="itemA">
요구사항 추가
- 판매 여부
- 판매 오픈 여부
- 체크 박스로 선택할 수 있다. - 등록 지역
- 서울, 부산, 제주
- 체크 박스로 다중 선택할 수 있다. - 상품 종류
- 도서, 식품, 기타
- 라디오 버튼으로 하나만 선택할 수 있다. - 배송 방식
- 빠른 배송
- 일반 배송
- 느린 배송
- 셀렉트 박스로 하나만 선택할 수 있다.
[ItemType - 상품 종류]
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;
private String displayName;
}
[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;
}
}
체크 박스 - 단일 1
단순 HTML 체크 박스
[resources/templates/form/addForm.html]
<hr class="my-4">
<!-- 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>
[FormItemController]
@PostMapping("/add")
public String addItem(@ModelAttribute Item item, RedirectAttributes redirectAttributes) {
log.info("item.open={}", item.getOpen());
. . .
** @Slf4j 애노테이션 추가
[실행 로그]
FormItemController : item.open=true //체크 박스를 선택하는 경우
FormItemController : item.open=null //체크 박스를 선택하지 않는 경우
[결과]


체크 박스를 체크하면 HTML Form에서 open=on 이라는 값이 넘어간다. 스프링은 스프링 타입 컨버터를 통해 on 이라는 문자를 true 타입으 로 변환해준다.
* 주의
체크 박스를 선택하지 않을 때
HTML에서 체크 박스를 선택하지 않고 폼을 전송하면 open이라는 필드 자체가 서버로 전송되지 않는다.
HTML 요청 메시지 로깅
HTTP 요청 메시지를 서버에서 보고 싶다면 다음 설정을 추가하자.
[application.properties]
logging.level.org.apache.coyote.http11=debug
HTML 체크 박스를 선택하지 않으면 클라이언트에서 서버로 값 자체를 보내지 않는다.
이게 수정의 경우 상황에 따라서 문제가 될 수도 있다. 사용자가 의도적으로 체크되어 있던 값을 해제하여도 저장시 아무 값도 넘어가지 않게 되기 때문이다 !! 이렇게 되면 서버 구현에 따라서 값이 오지 않은 것으로 판단해서 값을 수정하지 않을 수도 있다.
이 문제를 해결하기 위해 약간의 트릭을 사용한다.
히든 필드를 만들어서 체크 박스 이름 앞에 언더스코어(_)를 붙여서 전송하면 체크를 해제했다고 인식할 수 있게 한다 !!!
히든 필드는 항상 전송된다.
따라서 체크를 해제한 경우 위의 코드에서 open은 전송되지 않고, _open만 전송된다. 이 경우 스프링 MVC는 체크를 해제했다고 판단한다 !
체크 해제를 인식하기 위한 히든 필드
<input type="hidden" name="_open" value="on"/>
기존 코드에 히든 필드 추가
<!-- 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>
실행 로그
FormItemController: item.open=true //체크 박스를 선택하는 경우
FormItemController: item.open=false //체크 박스를 선택하지 않는 경우
체크 박스 체크
open=on&_open=on
체크 박스를 체크하면 스프링 MVC가 open에 값이 있는 것을 확인하고 사용한다. (이 때 _open은 무시함)
체크 박스 미체크
_open=on
체크 박스를 체크하지 않으면 스프링 MVC가 _open만 있는 것을 확인하고, open의 값이 체크되지 않았다고 인식한다.
체크하지 않았을 때 Boolean 값이 null이 아닌 false가 된다.
체크 박스 - 단일2
타임리프 - 체크 박스 코드 추가
<!-- 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>
타임리프 체크 박스 HTML 생성 결과
<!-- single checkbox -->
<div>판매 여부</div> <div>
<div class="form-check">
<input type="checkbox" id="open" class="form-check-input" name="open" value="true">
<input type="hidden" name="_open" value="on"/>
<label for="open" class="form-check-label">판매 오픈</label>
</div>
</div>
실행 로그
FormItemController: item.open=true //체크 박스를 선택하는 경우
FormItemController: item.open=false //체크 박스를 선택하지 않는 경우
[item.html]
<!-- 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>
* 주의
item.html 에는 th:object 를 사용하지 않았기 때문에 th:field 부분에 ${item.open} 으로 적어주어 야 한다.
HTML 생성 결과
<hr class="my-4">
<!-- single checkbox -->
<div class="form-check">
<input type="checkbox" id="open" class="form-check-input" disabled name="open" value="true" checked="checked">
<label for="open" class="form-check-label">판매 오픈</label>
</div>
[결과]
타임리프의 체크 확인
checked="checked"
체크 박스에서 판매 여부를 선택해서 저장하면 조회할 때 checked 속성이 추가된다.
타임리프의 th:field 를 사용하면, 값이 true 인 경우 체크를 자동으로 처리해준다.
[editForm.html]
<hr class="my-4">
<!-- 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()]
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());
}
[결과]
체크 박스 - 멀티
- 등록 지역
- 서울, 부산, 제주
- 체크 박스로 다중 선택할 수 있다.
[FormItemController]
@ModelAttribute("regions")
public Map<String, String> regions() {
Map<String, String> regions = new LinkedHashMap<>();
regions.put("SEOUL", "서울");
regions.put("BUSAN", "부산");
regions.put("JEJU", "제주");
return regions;
}
LinkedHashMap<>은 순서를 보장해준다. (HashMap은 순서보장 안됨)
* @ModelAttribute의 특별한 사용법
등록 폼, 상세화면, 수정 폼에서 모두 서울, 부산, 제주라는 체크 박스를 반복해서 보여주어야 한다. 이렇게 하려면 각각 의 컨트롤러에서 model.addAttribute(...)을 사용해서 체크 박스를 구성하는 데이터를 반복해서 넣어주어야 한다.
@ModelAttribute는 이렇게 컨트롤러에 있는 별도의 메서드에 적용할 수 있다.
이렇게하면 해당 컨트롤러를 요청할 때 regions에서 반환한 값이 자동으로 모델(model)에 담기게 된다. 물론 이렇게 사용하지 않고, 각각의 컨트롤러 메서드에서 모델에 직접 데이터를 담아서 처리해도 된다.
[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>
멀티 체크 박스는 같은 이름의 여러 체크박스를 만들 수 있지만, 태그 속성의 id는 모두 달라야 한다.
따라서 each 루프 안에서 반복해서 임의로 숫자를 붙여준다. : th:for="${#ids.prev('regions')}
each로 체크박스가 반복 생성된 결과 - id 뒤에 숫자가 추가
<input type="checkbox" value="SEOUL" class="form-check-input" id="regions1" name="regions">
<input type="checkbox" value="BUSAN" class="form-check-input" id="regions2" name="regions">
<input type="checkbox" value="JEJU" class="form-check-input" id="regions3" name="regions">
타임리프는 ids.prev(...) , ids.next(...) 을 제공해서 동적으로 생성되는 id 값을 사용할 수 있도록 한다.
타임리프 HTML 생성 결과
<!-- multi checkbox -->
<div>
<div>등록 지역</div>
<div class="form-check form-check-inline">
<input type="checkbox" value="SEOUL" class="form-check-input" id="regions1" name="regions">
<input type="hidden" name="_regions" value="on"/>
<label for="regions1"class="form-check-label">서울</label>
</div>
<div class="form-check form-check-inline">
<input type="checkbox" value="BUSAN" class="form-check-input" id="regions2" name="regions">
<input type="hidden" name="_regions" value="on"/>
<label for="regions2" class="form-check-label">부산</label>
</div>
<div class="form-check form-check-inline">
<input type="checkbox" value="JEJU" class="form-check-input" id="regions3" name="regions">
<input type="hidden" name="_regions" value="on"/>
<label for="regions3" class="form-check-label">제주</label>
</div>
</div>
<!-- -->
[결과]
로그 출력
[FormItemController.addItem()]
log.info("item.regions={}", item.getRegions());
서울, 부산 선택
regions=SEOUL&_regions=on®ions=BUSAN&_regions=on&_regions=on
로그: `item.regions=[SEOUL, BUSAN]`
지역 선택X
_regions=on&_regions=on&_regions=on
로그: `item.regions=[]`
[item.html]
<!-- 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>
* 주의
item.html에는 th:object 를 사용하지 않았기 때문에 th:field부분에 ${item.regions}으로 적어 주어야 한다.
타임 리프의 체크 확인
checked="checked"
타임리프는 th:field 에 지정한 값과 th:value의 값을 비교해서 체크를 자동으로 처리해준다.
[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>
[결과]
라디오 버튼
- 상품 종류
- 도서, 식품, 기타
- 라디오 버튼으로 하나만 선택할 수 있다.
[FormItemController]
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
return ItemType.values();
}
ItemType.values()를 사용하면 해당 ENUM의 모든 정보를 배열로 반환한다. 예) [BOOK, FOOD, ETC]
*(Mac) option + cmd + N : 인라인
[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>
[결과]

실행 결과, 폼 전송
itemType=FOOD //음식 선택, 선택하지 않으면 아무 값도 넘어가지 않는다.
로그 추가
log.info("item.itemType={}", item.getItemType());
실행 로그
item.itemType=FOOD: 값이 있을 때
item.itemType=null: 값이 없을 때
라디오 버튼은 이미 선택이 되어 있다면, 수정시에도 항상 하나를 선택하도록 되어 있으므로 체크 박스와 달리 별도의 히든 필드를 사용할 필요가 없다.
[item.html]
<!-- 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>
*주의
item.html에는 th:object를 사용하지 않았기 때문에 th:field부분에 ${item.itemType}으로 적어주어야 한다.
[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>
타임리프로 생성된 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" checked="checked">
<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>
[결과]
타임리프에서 ENUM 직접 사용
이렇게 모델에 ENUM을 담아서 전달하는 대신에 타임리프는 자바 객체에 직접 접근할 수 있다.
@ModelAttribute("itemTypes")
public ItemType[] itemTypes() {
return ItemType.values();
}
타임리프에서 ENUM 직접 접근
<div th:each="type : ${T(hello.itemservice.domain.item.ItemType).values()}">
${T(hello.itemservice.domain.item.ItemType).values()} 스프링EL 문법으로 ENUM을 직접 사용 할 수 있다. ENUM에 values() 를 호출하면 해당 ENUM의 모든 정보가 배열로 반환된다.
그런데 이렇게 사용하면 ENUM의 패키지 위치가 변경되거나 할때 자바 컴파일러가 타임리프까지 컴파일 오류를 잡을 수 없으므로 추천하지는 않는다 !!!
셀렉트 박스
- 배송 방식
- 빠른 배송
- 일반 배송
- 느린 배송
- 셀렉트 박스로 하나만 선택할 수 있다.
[FormItemController]
@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;
}
* 참고
@ModelAttribute가 있는 deliveryCodes() 메서드는 컨트롤러가 호출 될 때 마다 사용되므로 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">
타임리프로 생성된 HTML
<!-- SELECT -->
<div>
<DIV>배송 방식</DIV>
<select class="form-select" id="deliveryCode" name="deliveryCode">
<option value="">==배송 방식 선택==</option>
<option value="FAST">빠른 배송</option>
<option value="NORMAL">일반 배송</option>
<option value="SLOW">느린 배송</option>
</select>
</div>
[결과]
[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">
* 주의
item.html에는 th:object를 사용하지 않았기 때문에 th:field부분에 ${item.deliveryCode}으로 적어주어야 한다.
[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">
[타임리프로 생성된 HTML]
<!-- SELECT -->
<div>
<DIV>배송 방식</DIV>
<select class="form-select" id="deliveryCode" name="deliveryCode">
<option value="">==배송 방식 선택==</option>
<option value="FAST" selected="selected">빠른 배송</option>
<option value="NORMAL">일반 배송</option>
<option value="SLOW">느린 배송</option>
</select>
</div>
[결과]
'Tech > Spring | Spring Boot' 카테고리의 다른 글
[Spring][스프링 MVC 2편 - 백엔드 웹 개발 활용 기술] 4. 검증1 - Validation (1) | 2024.01.30 |
---|---|
[Spring][스프링 MVC 2편 - 백엔드 웹 개발 활용 기술] 3. 메시지, 국제화 (0) | 2024.01.30 |
[Spring][스프링 MVC 2편 - 백엔드 웹 개발 활용 기술] 1. 타임리프 - 기본 기능 (2) | 2024.01.25 |
[Spring][스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술] 7. 스프링 MVC - 웹 페이지 만들기 (1) | 2024.01.01 |
[Spring][스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술] 6. 스프링 MVC - 기본 기능 (2) | 2023.12.22 |
댓글