본문 바로가기

⭐ SpringBoot/SpringBoot + CRUD

[DELETE] 특정 폼의 데이터를 삭제하는 프로세스

# 아래와 같이 특정 폼의 데이터를 삭제하는 프로세스에 대해서 정리한다.

# 추가로 메인 리스트 화면에서 세부 페이지로 어떻게 이동하는지 보면 아래와 같다.

index.mustache 파일은 아래의 왼쪽 화면과 같이 페이지의 리스트를 보여주고 있으며, 해당 리스트의 세부 페이지로 이동하기 위해서는 오른쪽에 java 코드를 보면 알수 있다. href="/articles/{{id}}">{{title}} 로 이동한다.

그리고 href="/articles/{{id}}" 이 바라보는 대상은 Controller이다. 모든 href는 Controller의 API 주소를 바라본다고 볼 수 있다. 해당 컨트롤러를 살펴보면 아래와 같다. 위에서 href로 연결된 맵핑정보가 컨트롤러 객체 /articles/{{id}}를 호출하여 연산을 수행하고 수행된 정보를  articles/show 로 리턴해준다.

여기서 알아둬야 할 점은 return을 하는 대상과 href대상을 확인하는게 중요한데, return대상은 보통 frontend 객체인 html이나 mustache가 되고 href 대상은 API 맵핑 URL주소가 된다고 볼 수있다.

    @GetMapping("/articles/{id}")
    public String show(@PathVariable Long id, Model model) {
        log.info("id =" + id);

//        1. id로 데이터를 가져온다.
//        Article타입의 articleEntity라는 이름으로 데이터를 받아 온다.
//        해당 id 값을 찾았는데 만약 값이 없다면 null을 반환해라 라는 의미.
//        그래서 articleEntity라는 변수에는 값이 있거나 없으면 null 이라는 변수가 담기게 된다.
        Article articleEntity = articleRepository.findById(id).orElse(null);
        List<CommentDto> commentDtos = commentService.comments(id);

//        2. 가져온 데이터를 모델에 등록한다.
        model.addAttribute("article", articleEntity);
        model.addAttribute("commentDtos", commentDtos);
//        3. 보여줄 페이지를 설정한다.
        return "articles/show";
    }

1. 삭제대상 컨텐츠의 대상을 확인한다.

리스트 목록의 대상을 클릭하고 들어가면 아래와 같은 화면으로 이동한다.

Delete를 사용자가 클릭했을때 해당 게시물이 삭제되는 프로세스이다.

2. 삭제 코드를 보면 아래와 같다.

위의 화면을 표시하는 파일명은 show.mustache이고 해당 코드를 보면 아래와 같다.

@GetMapping("/articles/{id}") 에서 리턴으로 값을 show.mustache로 넘겨주고 해당 내용을 화면에 표시한다.

{{>layouts/header}}

<table class="table">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">Title</th>
        <th scope="col">Content</th>
    </tr>
    </thead>
    <tbody>
    {{#article}}
        <tr>
            <td>{{id}}</td>
            <td>{{title}}</td>
            <td>{{content}}</td>
        </tr>
    {{/article}}
    </tbody>
</table>

<a href="/articles/{{article.id}}/edit" class="btn btn-primary">Edit</a>
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>
<a href="/articles">Go to Article List</a>

{{>comments/_comments}}

{{>layouts/footer}}

위의 코드의 화면이 아래와 같다. 그리고 여기서 Delete를 클릭했을때 호출되는 API 정보가 href="/articles/{{article.id}}/delete" 이다.

3. 호출된 Delete API 코드를 보면 아래와 같다.

호출된 Delete API 코드를 보면 어렵지 않다. 일단 @PathVariable Long id 값을 가져와 삭제 대상을 조회하는데 사용한다.

그리고 해당 Long id 값이 존재하면 대상을 삭제한다. (아래 내용 참조)

그리고 모든 작업이 완료된 후 return "redirect:/articles"; 을 수행한다. 해당 명령은 index.mustache 파일을 호출한다.

    @GetMapping("/articles/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes rttr) {
        log.info("삭제 요청이 들어왔습니다!!");

        // 1. 삭제 대상을 가져온다.
        Article target = articleRepository.findById(id).orElse(null);
        log.info(target.toString());

        // 2. 대상을 삭제한다.
        if (target != null) {
            System.out.println(target.toString());
            articleRepository.delete(target);
            rttr.addFlashAttribute("msg", "삭제가 완료 되었습니다.");
        }

        // 3. 결과 페이지로 리 다이렉트 한다.
        return "redirect:/articles";
    }

그리고 RedirectAttributes rttr 은 잘 모르겠으나 삭제 했을때 화면에 삭제가 완료된 내용을 이미지로 표시하기 위해 사용하는것 같다.

삭제 까지의 프로세스를 알아봤다. 생각보다 복잡하다?