728x90
상품 수정 Controller
@GetMapping("/{itemId}/edit")
public String editForm(
@PathVariable Long itemId, Model model
) {
Item item = itemRepository.findById(itemId);
model.addAttribute("item", item);
return "basic/editForm";
}
상품 수정 뷰
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<link th:href="@{/css/bootstrap.min.css}"
href="../css/bootstrap.min.css" rel="stylesheet">
<style>
.container {
max-width: 560px;
}
</style>
</head>
<body>
<div class="container">
<div class="py-5 text-center">
<h2>상품 수정 폼</h2>
</div>
<form action="item.html" th:action method="post">
<div>
<label for="id">상품 ID</label>
<input type="text" id="id" name="id" class="form-control" value="1" th:value="${item.id}"
readonly>
</div>
<div>
<label for="itemName">상품명</label>
<input type="text" id="itemName" name="itemName" class="formcontrol" value="상품A" th:value="${item.itemName}">
</div>
<div>
<label for="price">가격</label>
<input type="text" id="price" name="price" class="form-control" th:value="${item.price}"
value="10000">
</div>
<div>
<label for="quantity">수량</label>
<input type="text" id="quantity" name="quantity" class="formcontrol" value="10" th:value="${item.quantity}">
</div>
<hr class="my-4">
<div class="row">
<div class="col">
<button class="w-100 btn btn-primary btn-lg" type="submit">저장
</button>
</div>
<div class="col">
<button class="w-100 btn btn-secondary btn-lg"
th:onclick="|location.href='@{/basic/items/{itemId}(itemId=${item.id})}'|"
onclick="location.href='item.html'" type="button">취소</button>
</div>
</div>
</form>
</div> <!-- /container -->
</body>
</html>
상품 수정 Action Controller
@PostMapping("/{itemId}/edit")
public String edit(
@PathVariable Long itemId, @ModelAttribute Item item
) {
itemRepository.update(itemId, item);
return "redirect:/basic/items/{itemId}";
}
- 리다이렉트
- 상품 수정은 마지막에 뷰 템플릿을 호출하는 대신에 상품 상세 화면으로 이동하도록 리다이렉트를 호출한다.
- 스프링은 redirect:/...으로 편리하게 리다이렉트를 지원한다.
-
return "redirect:/basic/items/{itemId}"; - 컨트롤러에 매핑된 @PathVariable 의 값은 redirect 에도 사용할 수 있다.
- 참고
- HTML Form 전송은 PUT, PATCH를 지원하지 않는다. GET, POST만 사용할 수 있다.
- PUT, PATCH는 HTTP API 전송시에 사용
- 스프링에서 HTTP POST로 Form 요청할 때 히든 필드를 통해서 PUT, PATCH 매핑을 사용하는 방법이 있지만, HTTP 요청상 POST 요청이다
728x90
'스프링 MVC 1편 (백엔드 웹 개발 핵심 기술)' 카테고리의 다른 글
| Ch07. 스프링 MVC(웹 페이지 만들기) - RedirectAttributes (0) | 2022.03.08 |
|---|---|
| Ch07. 스프링 MVC(웹 페이지 만들기) - PRG Post/Redirect/Get (0) | 2022.03.08 |
| Ch07. 스프링 MVC(웹 페이지 만들기) - 상품 등록 처리 (@ModelAttribute) (0) | 2022.03.08 |
| Ch07. 스프링 MVC(웹 페이지 만들기) - 상품 등록 폼 (0) | 2022.03.08 |
| Ch07. 스프링 MVC(웹 페이지 만들기) - 상품 상세 (0) | 2022.03.08 |