# 상품 수정

상품 상세 페이지에서 상품 수정을 클릭했을 때의 **"상품 수정"**&#xC744; 구현해본다.

![](https://4059345879-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdtAbfiAnzkPUNovpHX%2F-MeFYheaI-d9MLVUVjwK%2F-MeFYr913p12b2a-9BrG%2F%E1%84%89%E1%85%A1%E1%86%BC%E1%84%91%E1%85%AE%E1%86%B7%20%E1%84%89%E1%85%A1%E1%86%BC%E1%84%89%E1%85%A6.png?alt=media\&token=73b072d2-8231-421f-9ed1-28b8bc819d47)

상품 수정도 상품 등록과 유사하게 동일한 url("/{itemId}/edit") 에 대해 GetMapping과 PostMapping으로 메서드를 구현한다.

1. @GetMapping("/{itemId}/edit") : 단순 조희.\
   수정하려는 현재 item의 정보 조회

![](https://4059345879-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MdtAbfiAnzkPUNovpHX%2F-MeFYGaXCaG-IU-2x4v1%2F-MeFYUnaIrPpPiZPoaQ1%2F%E1%84%89%E1%85%A1%E1%86%BC%E1%84%91%E1%85%AE%E1%86%B7%20%E1%84%89%E1%85%AE%E1%84%8C%E1%85%A5%E1%86%BC%20%E1%84%91%E1%85%A9%E1%86%B7\(%E1%84%8C%E1%85%A5%E1%86%BC%E1%84%8C%E1%85%A5%E1%86%A8%E1%84%85%E1%85%B5%E1%84%89%E1%85%A9%E1%84%89%E1%85%B3%20GET\).png?alt=media\&token=593f0bef-6abc-4feb-9009-9bdc170551f6)

1. @PathVariable로 요청 url로 들어온 상품id와 Model을 파라미터로 갖는다.
2. itemId로 itemRepository에서 item 찾는다. Model에 찾은 item을 넣는다.
3. "basic/editForm" 페이지로 Model 전달한다!("basic/editForm 페이지로 이동)

```java
@GetMapping("/{itemId}/edit")
public String editForm(@PathVariable Long itemId,Model model){
    Item item = itemRepository.findById(itemId);
    model.addAttribute("item",item);//뷰에 전달할 객체 item!
    return "basic/editForm";//editForm 페이지로 데이터 전달한다!
}
```

2\. @PostMapping("/{itemId}/edit") : 정보 수정.\
HTML Form을 Post 방식으로 전송!

1. @GetMapping과 마찬가지로 @PathVariable itemId를 가져온다.
2. 수정할 데이터를 전송받는 것이기 때문에 @ModelAttribute를 이용하여 데이터들을 item 객체로 받는다!
3. itemRepository에 받은 객체 item을 update메서드 호출, 실행한다.
4. "/basic/items/{itemId}"로 **리다이렉트한다**!

```java
@PostMapping("/{itemId}/edit")
public String edit(@PathVariable Long itemId, @ModelAttribute Item item){
    itemRepository.update(itemId,item);
    return "redirect:/basic/items/{itemId}";
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/mvc/7.-mvc/undefined-6.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
