-
[Spring Boot] 수정기능Spring | SpringBoot 2024. 8. 16. 17:54
1. 글마다 수정버튼이 있는데 누르면 글수정 페이지로 이동
2. 그 페이지엔 폼이 있고 글의 내용이 이미 채워져있음
3. 전송누르면 그걸로 DB의 기존 글 수정
1. 버튼누르면 수정페이지로 이동
(list.html) <div class="card" th:each="i : ${items}"> <img src="https://placehold.co/300"> (생략) <a th:href="/???">✏️</a> </div>
@GetMapping("/edit") String edit() { return "edit.html"; }
수정페이지 보내줄 API
(edit.html) <form action="/???" method="POST"> <input name="title"> <input name="content"> <button type="submit">전송</button> </form>
수정페이지 html 파일
edit/1로 접속하면 1번글 내용이 채워진 수정페이지
/edit/2로 접속하면 2번글 내용이 채워진 수정페이지
... 이런식으로 만들고 싶으면
==> URL 파라미터 문법 사용
@GetMapping("/edit/{id}") String edit() { return "edit.html"; }
2. 그 페이지엔 폼이 있고 글 내용이 이미 채워져있음
/edit/1로 접속하면 1번 글의 내용이 채워져있어야한다
DB에서 1번 글 가져와서 여기다가 넣어주면 된다
// 상품 수정 기능 - 수정 페이지로 이동 @GetMapping("/edit/{id}") String edit(@PathVariable Long id, Model model) { // /edit/1로 접속하면 1번 글의 내용이 채워져있어야 하므로 db에서 1번글 가져와서 여기에 넣기 Optional<Item> result = itemRepository.findById(id); if(result.isPresent()) { model.addAttribute("data", result.get()); return "edit.html"; }else{ return "redirect:/list"; } }
가져와서 아래 html에 넣기
(edit.html) <form> <input name="title" th:value = "${data.title}"> <input name="price" th:value = "${data.price}"> <button type="submit">전송</button> </form>
3. 전송누르면 그걸로 DB의 기존 글 수정
(edit.html) <!--수정요청은 PUT이 깔끔하지만 form은 GET, POST만 가능--> <form action="/edit" method="POST"> <input name="id" th:value = "${data.id}"> <input name="title" th:value = "${data.title}"> <input name="price" th:value = "${data.price}"> <button type="submit">전송</button> </form>
전송누르면 /edit으로 POST 요청 날림
- JPA 사용해서 수정
// 상품 수정 기능 - 수정 페이지에서 수정 완료 후 원래 페이지에 반영 @PostMapping("/edit") String editItem(Long id, String title, Integer price) { // * JPA 사용해서 수정하려면 // 1. object 뽑고 // 2. object에 변수값 집어넣고 // 3. 그 다음에 save 안에 object 넣으면 됌 // (=> 원래 행 추가하는 문법이지만 id값이 같은 행이 이미 있으면 그 행 덮어쓰기 해줌) Item item = new Item(); item.setId(id); item.setTitle(title); item.setPrice(price); itemRepository.save(item); return "redirect:/list"; }
save는 행 하나 추가하는 문법이지만 id값이 같은 행이 이미 있으면 그 행을 덮어쓰기해준다
* 이글은 아래 강의를 참고해 작성했습니다.
https://codingapple.com/course/spring-boot-jpa/
쉽게 배우는 Spring Boot & JPA - 코딩애플 온라인 강좌
Next.js는 프론트엔드부터 서버까지 만들 수 있는 React기반 프레임워크입니다. 이것만 사용해도 풀스택 웹개발이 가능합니다. Next.js 사용시 서버사이드 렌더링이 쉽기 때문에 React, Vue만 사
codingapple.com
'Spring | SpringBoot' 카테고리의 다른 글
[Spring Boot] AJAX / 삭제 기능 (0) 2024.08.16 [Spring Boot] REST API의 예외처리 방법 / Service 레이어로 분리 (0) 2024.08.16 [Spring Boot] 상세페이지 만들기 / Optional / 예외처리 (0) 2024.08.12 [Spring Boot] 상품 추가기능 / th:fragment / th:replace (0) 2024.08.10 [Spring Boot] JPA / DB 데이터 출력 / HTML에 서버 데이터 넣기 (0) 2024.08.05