백/spring
[스프링부트3 자바 백엔드 개발 입문] 8장 - 게시글 삭제하기: Delete
복지희
2024. 1. 22. 00:09
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>
지난 포스트에서 만들었던 수정버튼 옆에 삭제버튼도 만든다.
HTML 에서 POST와 GET만 지원하고, DELETE는 지원하지 않아서 @DeleteMapping 이 아닌 @GetMapping으로 적어주겠다.
@GetMapping("articles/{id}/delete")
public String delete(@PathVariable Long id, Model model){
Article target = articleRepository.findById(id).orElse(null);
if(target != null){
articleRepository.delete(target);
}
return "redirect:/articles";
}
2번 id의 내용이 삭제된 것을 확인할 수 있다!! 와!!!!
삭제 완료 메세지 남기기
RedirectAttributes 객체의 addFlashAttribute() 메서드는 리다이렉트된 페이지에서 사용할 일회성 데이터를 등록할 수 있다.
@GetMapping("articles/{id}/delete")
public String delete(@PathVariable Long id, RedirectAttributes rttr){
...
if(target != null){
articleRepository.delete(target);
rttr.addFlashAttribute("msg", "삭제됐습니다!");
}
return "redirect:/articles";
}
한 번 쓰고 사라지는 휘발성 데이터를 등록하는 것이다.
msg에 담긴 메세지는 리다이렉트가 될 /articles 에서 사용할 수 있다.
articles를 띄워주는 index.mustache 파일을 보니, 이 파일안에서 보다는 header.mustache에서 메세지를 넣을 창을 추가해주는 게 낫겠다.
...
</nav>
{{#msg}}
<div class="alert alert-primary" role="alert">
{{msg}}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{{/msg}}
id가 2인 게시물이 사라지며 삭제됐습니다! 라는 문구가 뜨는 것을 확인할 수 있다!!!!