detail.html
<button id="deleteBtn" th:data-todo-no="${todo.todoNo}">삭제</button>
html 에서 th:date-* 로 todoNo 값 세팅
detail.js
const deleteBtn = document.querySelector("#deleteBtn");
deleteBtn.addEventListener("click", e => {
if (confirm("정말 삭제하시겠습니까?")) {
// 확인 눌렀을 때
location.href = `/todo/delete?todoNo=${e.target.dataset.todoNo}`;
}
});
e.target.dataset.todoNo html 에서 보내준 todoNo 값을
location.href 로 Controller에 Get 요청 보내주기 (queryString에 값 실어서)
TodoController
@GetMapping("delete")
public String todoDelete(@RequestParam("todoNo") int todoNo,
RedirectAttributes ra) {
int result = service.todoDelete(todoNo);
sql 에서 delete 구문 사용할 거라서 반환형이 int
service 호출해주기
ServiceImpl
@Override
public int todoDelete(int todoNo) {
return mapper.todoDelete(todoNo);
}
TodoMapper interface
int todoDelete(int todoNo);
todo-mapper.xml
<delete id="todoDelete" parameterType="_int">
DELETE FROM TB_TODO
WHERE TODO_NO = #{todoNo}
</delete>
Controller
매개변수에 RedirectAttributes ra 추가
String path = null;
String message = null;
if(result > 0) { // 성공
// 메인 페이지로 리다이렉트
message = "삭제 성공";
path = "/";
} else { // 실패
path = "/todo/detail?todoNo=" + todoNo;
message = "삭제 실패";
}
ra.addFlashAttribute("message", message);
return "redirect:" + path;
}
ra에 message 실어서 보내줌