현재 이미지를 누르면 상세페이지로 넘어가는데 수정 기능이 있으면 좋겠다

 

<div class="card" th:each="item : ${items}">
    <a th:href="@{'/detail/' + ${ item.id } }">
        <img src="https://placehold.co/300">
    </a>
    <div>
        <h4 th:text="${item.title}"></h4>
        <p th:text="${item.price}"></p>
        <a th:href="@{'/modify/' + ${ item.id } }">
            <button >수정</button>
        </a>

    </div>
</div>

모든 상품목록에 수정 기능이 필요하니 타임리프 반복문 안에 a태그로 modify로 id값을 가져가게 만들어준다

 

@GetMapping("/modify/{id}")
String modify(Model model,
              @PathVariable Integer id) {
    var item = itemService.findById(id);
    if (item.isPresent()) {
        model.addAttribute("detail", item.get());
    } else {
        return "redirect:/list";
    }
    return "modify";
}

url로 이동하게 만들어뒀으니 그걸 잡아주는 컨트롤러가 필요하다

GetMapping 같은 경우는 modify/변하는 id 값으로 받아주고

먼저 기본적으로 등록되있는 값을 보여주기 위해 modify라는 html안에

데이터베이스 안에 아이템의 정보를 넣어준다

또 널값일 수 있으니 if문으로 해주고

modify.html을 반환

 

<form action="/update" method="POST">
    <input type="hidden" th:value=${detail.id} name="id">
    <input type="text" th:value="${detail.title}" name="title">
    <input type="text" th:value="${detail.price}" name="price">
    <button type="submit" > 수정완료 </button>
</form>

 

id 값은 보일 필요는 없지만 쓸 곳이 있으니 히든으로 생성해놓는다

또 여기서 th:value라는게 있는데 input 태그 안에 기본적으로 값이 들어가있으려면

th:value를 사용해서 채워놓을 수 있다

그리고 이번에도 사용자에게 받은 값을 전송해야하기 때문에 form 태그 안에 감싸준다

이번엔 update로 보내주기 때문에

컨트롤러로 넘어간다

 

@PostMapping("/update")
String modifyPost(Integer id,String title, Integer price) {
    itemService.modify(id, title, price);
    return "redirect:/list";
}

 

update로 들어왔을 때 id, title, price 값을 기본 id값과 사용자에게 받은 title, price 값을 가지고 또 서비스로 넘어간다

 

public void modify(Integer id, String title, Integer price) {
    var item = itemRepository.findById(id).orElse(null);
    item.setTitle(title);
    item.setPrice(price);
    itemRepository.save(item);
}

 

이건 서비스 쪽에 modify인데

일단 save 라는게 새로 추가하는 뜻도 있는데

자체가 id값이 중복되는 값이 있을경우 수정으로 바뀌게 된다고 한다

또 save 안에는 Entity 객체가 들어와야하는데

var item = itemRepository.findById(id)

 

이렇게만 받아왔을 경우

Optional

 

상태이기 때문에 .orElse(null)로 변경해주는거 같다

gpt가 orElse(null)은 엔티티가 존재하지 않을 경우 null을 반환하는 방법이라고 한다

맞는거같다

이렇게 수정기능 완성 ~

 

+ 강의 확인해보니 save 라는게 새로운 Entity여도 id값이 중복이면 수정이 가능하다

public void modify(Integer id, String title, Integer price) {
    Item item = new Item();
    item.setId(id);
    item.setTitle(title);
    item.setPrice(price);
    itemRepository.save(item);
}

 

이런식으로도 접근이 가능하다 !

'SpringBoot' 카테고리의 다른 글

회원가입 구현  (1) 2024.10.21
AJAX를 통한 삭제 기능  (2) 2024.10.21
REST API 에러처리  (1) 2024.10.18
에러 처리  (1) 2024.10.18
상품 상세 페이지  (1) 2024.10.16

+ Recent posts