Post

[Spring Boot] 게시글 삭제하기: Delete

데이터 삭제 과정

게시판에서 글을 삭제하는 과정은 다음 순서대로 이루어진다.

  1. 클라이언트가 HTTP 메서드로 특정 게시글의 삭제를 요청한다.
  2. 삭제 요청을 받은 컨트롤러는 리파지터리를 통해 DB에 저장된 데이터를 찾아 삭제한다. (기존 데이터가 있는 경우)
  3. 삭제가 완료됐다면 클라이언트를 결과 페이지로 리다이렉트 한다.

데이터 삭제하기

View에 Delete 버튼 추가하기

먼저 해당 글을 삭제할 수 있도록 상세 페이지 뷰에 삭제 버튼을 추가한다.

1
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>

삭제 시에도 마찬가지로 어떤 게시글을 삭제할 것인지 id값을 함께 보내주야 한다.

Delete 요청을 받아 데이터 삭제하기

HTTP 메서드에 따르면 삭제할 때는 DELETE 메서드를 사용해야 한다. 그러나 HTML에서는 POST와 GET을 제외한 다른 메서드를 제공하지 않는다.

지금은 GET 방식으로 삭제 요청을 받아 처리하는 방법을 알아본다.

Controller에 삭제 요청을 받아 처리할 delete() 메서드를 추가한다.

1
2
3
4
@GetMapping("/articles/{id}/delete")
    public String delete() {
        return null;
    }

원래대로라면 @DeleteMapping을 사용해야 하지만, HTML에서 DELETE 메서드를 지원하지 않아 @GetMapping을 사용한다.

삭제할 대상 가져오기

DB에 접근해 데이터를 처리할 때는 JPA의 리파지터리를 이용한다.

articleRepository.findById(id) 메서드로 DB에 해당 id를 가진 데이터가 있는지 찾는다. 만약 찾으면 엔티티 타입의 target 변수에 젖아하고, 찾지 못하면 null을 반환한다.

findById 메서드에서 사용한 변수 id@PathVariable 어노테이션을 사용해 URL 주소에서 가져온 id 값이다.

1
2
3
4
5
    @GetMapping("/articles/{id}/delete")
    public String delete(@PathVariable Long id) {
        Article target = articleRepository.findById(id).orElse(null);
        return null;
    }

대상 엔티티 삭제하기

target에 무언가 저장됐다면 삭제를 수행한다.

1
2
3
if (target != null) {
            articleRepository.delete(target);
        }

결과 페이지로 리다이렉트 하기

게시글 삭제 후 목록 페이지로 돌아가도록 한다.

1
return "redirect:/articles";

Delete result - 1

Delete result - 2

Delete result - 3

정상적으로 삭제가 완료되고 있음을 알 수 있다.

삭제 완료 메시지 남기기

RedirectAttributes 객체를 이용해 리다이렉트 페이지에서 사용할 데이터를 남길 수 있다.

이 객체를 사용해서 삭제 후 삭제 완료 메시지를 남겨보자.

RedirectAttributesaddFlashAttribute() 메서드를 활용하면 리다이렉트 시점에 한 번만 사용할 휘발성 데이터를 등록할 수 있다.

1
2
3
4
5
6
7
8
9
    @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 키 값에 담긴 메시지는 리다이렉트 된 페이지에서 사용할 수 있다.

1
2
3
4
5
6
{{#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}}

templates/articles/layouts/header.mustache

헤더 파일에 다음과 같이 추가해주어 삭제 시 알림창을 통해 메시지를 띄워주도록 했다.

Delete result - 4

🔗 참고자료

📚 더 공부해야 할 것

  • @DeleteMapping
  • RedirectAttributes, addFlashAttribute()
  • HTTP DELETE
This post is licensed under CC BY 4.0 by the author.