데이터 삭제 과정(출처)
클라이언트가 HTTP 메서드로 특정 게시글의 삭제를 요청.컨트롤러 -> 리파지터리 -> DB에 저장된 데이터를 찾아서 삭제함.기존 데이터가 있을 경우.클라이언트를 결과 페이지로 리다이렉트함.
리다이렉트된 페이지에서 일회용으로 사용할 데이터 등록해서 보내기(출처)

결과 페이지로 리다이렉트할 때 클라이언트에 삭제완료 메시지 띄워주기.인터페이스가 RedirectAttributes임.RedirectAttributes객체의 addFlashAttribute()라는 메서드는 리다이렉트된 페이지에서 사용할 일회성 데이터를 등록할 수 있음.상세 페이지에 삭제 버튼 추가.<a href="/articles/{{article.id}}/delete" class="btn btn-danger">삭제</a>

클라이언트에서 서버로 요청을 보낼 때 크게 4가지의 HTTP메서드를 활용함.POST, GET, PATCH(PUT), DELETEDELETE를 사용해야 됨.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 idURL에 있는 {id} 변수를 사용.Article target = articleRepository.findById(id).orElse(null);id변수로 findById()메서드를 통해 데이터 조회.return "redirect:/articles";목록 페이지로 돌아가야됨.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 사용 범위 지정.
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();
}