728x90
* 학습목표
Article 데이터를 DB에서 삭제하고, 이를 확인하시오.
데이터 삭제 흐름 3단계
1. 데이터 전달이 되면 /articles/{id}/delete
2. DB에서 찾고 삭제한다음에
3. index 결과페이지로 redirect한다, 삭제되면 알람 메세지 출력.
실습개요
삭제버튼추가
templates/show.mustache 에 button 추가.
<a href="/articles/{{article.id}}/delete" class="btn btn-danger">Delete</a>
//빨간색 버튼
삭제요청받기
<메서드 추가>
//@DeleteMapping("articles/{id}/delete")
HTML에서 공식적으로 지원하지 않아서
@GetMapping("articles/{id}/delete")
요청을 받아옵시다.
public Stirng delete(){
log.info("삭제 요청이 들어왔습니다!!");
return null;
}
log 확인.
2022-05-04 20:20:35.700 INFO 16212 --- [nio-8080-exec-4] c.e.f.controller.ArticleController : 삭제 요청이 들어왔습니다!!
삭제 처리 개요
1: 삭제 대상을 가져온다!
2: 대상을 삭제 한다!
3: 결과 페이지로 리다이렉트 한다!
삭제 대상 가져오기
1: 삭제 대상을 가져온다!
Article target = articleRepository.findById(id).orElse(null);
//만약에 없다면 null값을 가져와라.
//id는 URL에서 가져올 수 있다.
@GetMapping("articles/{id}/delete") 여기서 {id}값을 가져오기 위해.
public String delete(@PathVariable Long id){
//여기 있는 Long id 이 URL에 있는 {id}가 되기 위해선
//@PathVariable 어노테이션을 사용해주면 된다.
대상 엔티티 삭제.
if(target != null){
//데이터가 있다면
articleRepository.delete(target);
//삭제한다(무엇을?) 앞에서 찾아온 삭제 대상(target)을
}
리다이렉트
return "redirect:/articles";
//삭제가 되면 목록페이지로 리다이렉트(articles 페이지를 재요청)
삭제 완료 메세지
public String delete(@PathVariable Long id, RedirectAttributes rttr){
//얘를 가지고 삭제가 된 경우에 rttr.addFlashAttribute 메서드를 통해서
//일회성.
//("msg라는 키값에", "삭제가 완료되었습니다! 라는 메세지를 쓸 수있다.")
rttr.addFlashAttribute("msg", "삭제가 완료 되었습니다!");
근데 이게 보내지는 곳이 어디라고?
return "redirect:/articles";
//여기라구 ~
그럼 알람 메시지 출력을 위해
index.mustache 파일의 header 부분에 msg 부분을 추가할꺼임.
<!-- alert msg -->
{{#msg}}
//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}}
//이 안에있는걸 출력해라.
SQL 삭제
DELETE article
// 삭제할꺼야 article 테이블에서
WHERE id = 3;
// id = 3값의 데이터를
요약
1. localhost:8080/articles 로 접속해서
2. Delete 버튼을 눌러서 삭제요청을 했을때
3. 이 요청을 어떻게 받더라?
4. @GetMapping("articles/{id}/delete") 을 통해 받는다.
5. id 값을 가져오는데
6. @PathVariable Long id 로 가져오는데 이놈을 가지고
7. Article target = articleRepository.findById(id).orElse(null); DB에서 대상을 찾고
8. 찾아졌다면 삭제합니다.
if(target != null){
articleRepository.delete(target);
}
9. 삭제가 되었다면 리다이렉트를 통해 목록으로 돌아가는데
return "redirect:/articles";
10. 삭제가 되었다는걸 알려주기 위해서 알람메세지를 띄우기 위해.
public String delete(@PathVariable Long id, RedirectAttributes rttr){
//이 객체를 통해서
rttr.addFlashAttribute("msg", "삭제가 완료 되었습니다!");
데이터를 등록할 수 있었다.
https://github.com/Giltaehyeong/firstproject/commit/cac09835e67c7adce9d822a52cc3ea11be199660
[스프링 부트 입문 16]데이터 삭제하기 · Giltaehyeong/firstproject@cac0983
* 학습목표 Article 데이터를 DB에서 삭제하고, 이를 확인하시오. 데이터 삭제 흐름 3단계 1. 데이터 전달이 되면 /articles/{id}/delete 2. DB에서 찾고 삭제한다음에 3. index 결과페이지로 redirect한다, 삭제
github.com
소스코드참고.
728x90
'Back-End > SpringBoot' 카테고리의 다른 글
| [스프링 부트 입문 17]CRUD와 SQL 쿼리 (0) | 2022.05.05 |
|---|---|
| [스프링 부트 입문 15]데이터 수정하기 (0) | 2022.05.04 |
| [스프링 부트 입문 14]수정 폼 만들기 (0) | 2022.05.04 |
| [스프링 부트 입문 13]링크와 리다이렉트 (0) | 2022.05.03 |
| [스프링 부트 입문 12]데이터 목록조회 (0) | 2022.05.03 |