8일차 - 게시글 삭제하기: Delete
2024. 8. 7. 12:24ㆍ코딩 자율학습 스프링 부트3 자바 백엔드 개발 입문 스터디
데이터 삭제 과정
- 클라이언트가 HTTP 메서드로 특정 게시글의 삭제를 요청한다.
- 삭제 요청을 받은 컨트롤러는 레포티조티를 통해 DB에 저장된 데이터를 찾아 삭제한다.
- 삭제가 완료됐다면 클라이언트를 결과 페이지로 리다이렉트 한다.
RedirectAttributes 객체를 사용하면 addFlashAttribute() 라는 메서드를 이용하여 리다이렉트된 페이지에서 사용할 일회성 데이터를 등록할 수 있다.
데이터 삭제하기
Delete 버튼 추가
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>
- 상세 페이지에서 요청보낼 URL과 삭제 버튼을 생성한다.
Delete 요청을 받아 데이터 삭제하기
@GetMapping("/articles/{id}/delete")
public String delete(@PathVariable Long id) {
log.info("삭제 요청");
Article target = articleRepository.findById(id).orElse(null);
log.info("레포지토리에서 id 조회 : " + target.toString());
if (target != null) {
articleRepository.delete(target);
log.info("삭제 완료 글 : " + target.toString());
}
return "redirect:/articles";
}
- delete() 메소드
- 요청받을 URL 을 매핑해준다.
- 삭제할 대상 가져오기
- 레포지토리에서 id 값을 조회하여 데이터가 있는지 확인한다.
- 대상 엔티티 삭제하기
- 레포지토리에서 가져온 데이터가 null 이 아니라면 delete() 를 사용하여 삭제한다.
- 결과 페이지로 리다이렉트
- 게시글을 삭제하면 목록 페이지로 돌아가게 설정한다.
삭제 완료 메시지 남기기
@GetMapping("/articles/{id}/delete")
public String delete(@PathVariable Long id, RedirectAttributes rttr) {
log.info("삭제 요청");
Article target = articleRepository.findById(id).orElse(null);
log.info("레포지토리에서 id 조회 : " + target.toString());
if (target != null) {
articleRepository.delete(target);
log.info("삭제 완료 글 : " + target.toString());
rttr.addFlashAttribute("msg", "삭제 완료");
}
return "redirect:/articles";
}
- 리다이렉트 페이지에서 사용할 데이터를 남기기 위해 RedirectAttributes 를 활용한다. delete() 메서드의 매개변수로 받아와야 한다.
- addFlashAttribute() 를 활용하면 리다이렉트 시점에 한 번만 사용할 데이터를 등록할 수 있다.
객체명.addFlashAttributes(attributeName, attributeValue);
- 헤더에 메시지를 출력하기 위하여 작성한다.
{{#msg}}
<div class="alert alert-primary alert-dimissible">
{{msg}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/msg}}
SQL DB 삭제
DELETE FROM 테이블명 WHERE 조건;
'코딩 자율학습 스프링 부트3 자바 백엔드 개발 입문 스터디' 카테고리의 다른 글
10일차 - REST API와 JSON (0) | 2024.08.09 |
---|---|
9일차 - CRUD와 SQL 쿼리 종합 (0) | 2024.08.08 |
7일차 - 게시글 수정하기: Update (0) | 2024.08.06 |
6. 게시판 내 페이지 이동하기 (0) | 2024.08.05 |
5일차 - 게시글 읽기 : Read (0) | 2024.08.02 |