Spring Boot To do List_07 할 일 삭제

송지윤·2024년 4월 15일
0

Spring Framework

목록 보기
23/65
  1. 상세조회 페이지에서 삭제 버튼 클릭했을 때 js 로 todoNo 넘겨주기
  2. js에서 버튼 눌렀을 때 클릭 이벤트 추가해서 controller로 todoNo 넘겨주기
  3. Controller에서 값 받아서 service 호출
  4. mapper.xml 에서 sql 실행 후 값 반환
  5. Controller 에서 돌려 받은 값으로 분기처리

1. 상세조회 페이지에서 삭제 버튼 클릭했을 때 js 로 todoNo 넘겨주기

detail.html

<button id="deleteBtn" th:data-todo-no="${todo.todoNo}">삭제</button>

html 에서 th:date-* 로 todoNo 값 세팅

2. js에서 버튼 눌렀을 때 클릭 이벤트 추가해서 controller로 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에 값 실어서)

3. Controller에서 값 받아서 service 호출

TodoController

	@GetMapping("delete")
	public String todoDelete(@RequestParam("todoNo") int todoNo,
			RedirectAttributes ra) {
		
		int result = service.todoDelete(todoNo);

sql 에서 delete 구문 사용할 거라서 반환형이 int
service 호출해주기

4. mapper.xml 에서 sql 실행 후 값 반환

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>

5. Controller 에서 돌려 받은 값으로 분기처리

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 실어서 보내줌

0개의 댓글