RedirectAttributes 객체
로 리다이렉트 페이지에서 사용할 데이터를 남길 수 있음.
RedirectAttributes
를 활용하려면 메서드의 매개변수로 받아와야함.RedirectAttributes 객체
의 addFlashAttribute()
메서드를 활용하면 리다이렉트
시점에 한 번만 사용할 데이터
를 등록할 수 있음.
휘발성 데이터
를 등록하는 것.↓ 형식
객체명.addFlashAttribute(넘겨 주려는 키 문자열, 넘겨 주려는 값 객체)
RedirectAttributes
의 addFlashAttribute()
메서드는 내부적으로 HttpSession을 이용
하여 일시적으로 데이터를 저장하고 리다이렉트 이후에 한 번 사용
되면 자동으로 세션에서 제거
됨. @GetMapping("/articles/{id}/delete")
public String delete(@PathVariable Long id, RedirectAttributes rttr) { // 데이터 삭제.
Article target = articleRepository.findById(id).orElse(null);
if (target != null) {
articleRepository.delete(target);
// 넘겨주려는 키 문자열(msg), 넘겨 주려는 값 객체(삭제 완료.)
rttr.addFlashAttribute("msg", "삭제 완료.");
}
return "redirect:/articles";
}
msg
에 담긴 삭제 완료
메시지는 반환하는 뷰 페이지
에서 사용함./articles
페이지에서 보여줌.<!-- 삭제 완료 메시지 알림 -->
{{#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 키
를 사용할 범위를 잡음.메시지 창(alert)
으로 msg에 담긴 값을 출력
하고 닫기 버튼
을 추가.<!-- 메시지가 존재할 때만 표시 -->
<div th:if="${msg}" class="alert alert-primary alert-dismissible">
<span th:text="${msg}"></span>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<div th:if="${msg}" class="alert alert-primary alert-dismissible fade show" role="alert">
<span th:text="${msg}"></span>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
class 속성 차이
항목 | 첫 번째 코드 | 두 번째 코드 |
---|---|---|
class 값 | alert alert-primary alert-dismissible | alert alert-primary alert-dismissible fade show |
fade show