[Spring Boot] Day8 - Delete

Sarah·2025년 12월 7일

Spring Boot

목록 보기
9/17

오늘의 목표

앞서 만든 게시판에서 등록된 글을 삭제하는 기능을 구현하기

Delete 버튼 추가하기

  • 상세 뷰 페이지에서 Delete 버튼을 추가한다.
		<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>

Delete 메서드 만들기

    @GetMapping("/articles/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes rttr) {
        log.info("삭제 요청이 들어왔습니다!");
        Article target = articleRepository.findById(id).orElse(null);
        log.info(target.toString());
        if(target!=null) {
            articleRepository.delete(target);
            rttr.addFlashAttribute("msg", "삭제됐습니다!");
        }
        return "redirect:/articles";
    }

@GetMapping("/articles/{id}/delete")
  • 뷰 페이지의 Delete 버튼에서 이동되는 연결 링크를 "/articles/{{id}}/delete"로 지정했으니, 해당 url이 요청되면 실행되는 메서드로 만들기.
public String delete(@PathVariable Long id, RedirectAttributes rttr) 
  • GetMapping에 있는 id를 그대로 매개변수로 가져오도록 @PathVariable 어노테이션 추가, RedirectAttributes 객체 가져오기

RedirectAttributes

  • 리다이렉트할 때 데이터를 안전하게 넘기기 위해 사용
  • 뷰 페이지에서 데이터를 넘길 때는 보통 Model을 사용.
  • 하지만 return 에서 redirect(리다이렉트)를 사용하면 다시 다른 URL으로 이동(새로운 요청 발생)하기 때문에 일반 Model을 넣은 값은 리다이렉트 후 사라져서 전달되지 않음.
Article target = articleRepository.findById(id).orElse(null);
  • 전달된 id(삭제하고 싶은)에 해당하는 데이터를 찾아 target이라는 이름의 엔티티에 저장해주기
if(target!=null) {
            articleRepository.delete(target);
            rttr.addFlashAttribute("msg", "삭제됐습니다!");
        }
  • 전달된 id의 데이터가 있다면 -> 리포지터리 사용해서 해당 엔티티 삭제 (delete)
  • RedirectAttributes 객체인 rttr의 addFlashAttribute 메서드 사용
public String delete(@PathVariable Long id, RedirectAttribute rttr) {
rttr.addFlashAttribute(넘겨 주려는 키 문자열, 넘겨 주려는 값 객체);
  • addFlashAttribute리다이렉트 후 1회성 메시지를 전달하고 싶을 때 사용

삭제 완료 메시지 남기기

  • addFlashAttribute("msg", "삭제됐습니다!"); -> msg라는 키 문자열에 "삭제됐습니다!" 라는 값 메세지 넣음.
  • msg 키 값에 담긴 메시지는 <delete 메서드의 return>에서 보여줘야 함. -> index.mustache / 하지만 header.mustache에 출력하는게 낫다.
{{#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}}
  • header.mustache 맨 아래 코드 추가하기
profile
헤맨 만큼 내 땅

0개의 댓글