1. 데이터 삭제 과정.

데이터 삭제 과정(출처)

  • 클라이언트HTTP 메서드로 특정 게시글의 삭제를 요청.
  • 요청을 받은 컨트롤러 -> 리파지터리 -> DB에 저장된 데이터를 찾아서 삭제함.
    • 기존 데이터가 있을 경우.
  • 삭제가 완료되었다면 클라이언트결과 페이지리다이렉트함.

리다이렉트된 페이지에서 일회용으로 사용할 데이터 등록해서 보내기(출처)

  • 결과 페이지리다이렉트할 때 클라이언트에 삭제완료 메시지 띄워주기.
    • 이를 위한 인터페이스RedirectAttributes임.
    • RedirectAttributes객체의 addFlashAttribute()라는 메서드는 리다이렉트된 페이지에서 사용할 일회성 데이터를 등록할 수 있음.

2. 데이터 삭제하기.


2-1. 삭제 버튼 추가하기.

  • 상세 페이지에 삭제 버튼 추가.
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">삭제</a>


2-2. 삭제 요청 받기.

  • 클라이언트에서 서버로 요청을 보낼 때 크게 4가지의 HTTP메서드를 활용함.
    • POST, GET, PATCH(PUT), DELETE
      • 삭제 요청이니 DELETE를 사용해야 됨.
    • but HTML에서는 POST, GET을 제외한 다른 메서드를 제공하지 않음.
    • 따라서 GET 방식으로 삭제 요청을 받아서 처리하기로.
    @GetMapping("/articles/{id}/delete")
    public String delete(@PathVariable Long id) {
        Article target = articleRepository.findById(id).orElse(null);
        if (target != null) {
            articleRepository.delete(target);
        }
        return "redirect:/articles";
    }
  • @GetMapping("/articles/{id}/delete")
    • 앞서 말한 GET 방식.
  • @PathVariable Long id
    • URL에 있는 {id} 변수를 사용.
  • Article target = articleRepository.findById(id).orElse(null);
    • 가져온 id변수로 findById()메서드를 통해 데이터 조회.
  • return "redirect:/articles";
    • 게시글을 삭제하면 목록 페이지로 돌아가야됨.

2-3. 삭제 완료 메시지.

  • 매개변수를 통해 RedirectAttributes의 객체를 받음.
  • RedirectAttributes 객체의 addFlashAttribute() 메서드를 이용하면 리다이렉트시점에 일회용으로 사용할 데이터를 등록할 수 있음.
    • 즉, 한 번 쓰고 사라지는 휘발성데이터.

사용 형식.

객체명.addFlashAttribute(넘겨 주려는 키(문자열), 넘겨주려는 값(객체))
if (target != null) {
    articleRepository.delete(target);
    rttr.addFlashAttribute("msg", "삭제 완료.");
}
  • "msg"키 값에 담긴 메시지목록 페이지에서 보여줄 메시지이므로 목록 페이지 소스코드 수정이 필요한데 헤더(header)쪽 코드를 수정하는 걸로 결정.
{{#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}}
  • {{#msg}} ~ {{/msg}}
    • msg 사용 범위 지정.


3. interface RedirectAttributes.

import java.util.Collection;
import java.util.Map;
import org.springframework.lang.Nullable;
import org.springframework.ui.Model;

public interface RedirectAttributes extends Model {
    RedirectAttributes addAttribute(String attributeName, @Nullable Object attributeValue);

    RedirectAttributes addAttribute(Object attributeValue);

    RedirectAttributes addAllAttributes(Collection<?> attributeValues);

    RedirectAttributes mergeAttributes(Map<String, ?> attributes);

    RedirectAttributes addFlashAttribute(String attributeName, @Nullable Object attributeValue);

    RedirectAttributes addFlashAttribute(Object attributeValue);

    Map<String, ?> getFlashAttributes();
}
profile
Every cloud has a silver lining.

0개의 댓글