👉 Mission. Article 데이터를 DB에서 삭제하시오
<데이터 삭제 흐름>
1. 삭제 요청 전달
2. DB에서 데이터 찾고 삭제한 다음
3. 결과 페이지 redirect
1. 삭제 버튼 생성
참고로 아직 html로만 작성하고 있어 요청이 GET과 POST만 지원되니 나중에 JS를 사용해서 PATCH(PUT), DELETE를 사용하도록 수정할 예정!
2. DB에서 데이터 삭제 - controller
파일명 : controller/ArticleController.java
@GetMapping("/articles/{id}/delete")
public String delete(@PathVariable Long id){
//1. 삭제 대상을 가져오기
Article target = articleRepository.findById(id).orElse(null);
log.info(target.toString());
//2. 그 대상을 삭제
if(target != null){
articleRepository.delete(target);
}
//3. 결과 페이지로 리다이렉트
return "redirect:/articles";
}
반드시 삭제할 데이터가 DB에 있을 경우 삭제해야함!
여기까지해도 데이터 삭제는 정상적으로 처리되지만 뭔가 아쉬우니 '삭제 메시지'를 남겨줘보자.
📌 삭제 메시지 띄우기
1. RedirectAttributes를 사용해 redirect시 사용할 데이터를 전달
RedirectAttributes = redirect시 데이터를 전달할 수 있는 방법 중 하나
파일명 : controller/ArticleController.java
@GetMapping("/articles/{id}/delete")
public String delete(@PathVariable Long id, RedirectAttributes rttr){
...
//2. 그 대상을 삭제
if(target != null){
...
rttr.addFlashAttribute("msg", "삭제가 완료되었습니다.");
}
...
}
addAttribute
: 값을 지속적으로 사용해야할 때addFlashAttribute
: 값을 일회성으로 사용해야할 때2. 페이지에 알림을 보이게 설정
페이지의 헤더 영역에 알림을 보이게 설정하기
파일명 : templates/layouts/header.mustache
...
<!-- alert message -->
{{#msg}}
<div class="alert alert-primary alert-dismissible">
{{msg}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/msg}}
<데이터 삭제 흐름>
1. 삭제 요청 전달
2. DB에서 데이터 찾고 삭제한 다음
3. 결과 페이지 redirect
강의 출처 : https://www.youtube.com/watch?v=_vDACE13Ubc&list=PLyebPLlVYXCiYdYaWRKgCqvnCFrLEANXt&index=1 [스프링 부트 입문 - 홍팍]