๊ธ ์ญ์ ๋ javascript๋ฅผ ์ด์ฉํ ๊ฒ์ด๋ค.
์์ธํ์ด์ง์์ ์ญ์ ๋ฒํผ์ id๋ฅผ ๋ฃ๊ณ , board.js ๊ฐ ์๋ํ๋ค.
.
.
.
<button id="btn-delete" class="btn btn-danger">์ญ์ </button>
.
.
.
<script src="/js/board.js"></script>
<%@ include file="../layout/footer.jsp"%>
์ฌ๊ธฐ์ ๊ธ์ ์ด ์ ์ (๋ณธ์ธ)๋ง ์ญ์ ๋ฒํผ์ ๋ณผ ์ ์์ด์ผ ํ๋ค. ๋ค๋ฅธ ์ ์ ๊ฐ ๊ธ์ ์ญ์ ํ๋ฉด ์๋๊ธฐ ๋๋ฌธ์ด๋ค.
๋ฐ๋ผ์
<c:if test="${board.user.id == principal.user.id}">
<button id="btn-delete" class="btn btn-danger">์ญ์ </button>
</c:if>
์์ฒ๋ผ if๋ฌธ์ ๊ฑธ์ด์ฃผ๋ฉด ๋๋ค.
let index = {
init: function () {
.
.
.
$("#btn-delete").on("click", ()=>{
this.deleteById();
});
},
.
.
.
deleteById: function () {
var id = $("#id").text();
$.ajax({
type: "DELETE",
url: "/api/board/"+id,
dataType: "json"
}).done(function (resp) {
// ๊ฒฐ๊ณผ๊ฐ ์ ์์ด๋ฉด done ์คํ
alert("๊ธ์ญ์ ๊ฐ ์๋ฃ๋์์ต๋๋ค.");
location.href = "/";
}).fail(function (error) {
// ์คํจํ๋ฉด fail ์คํ
alert("๊ธ์ญ์ ๋ฅผ ์คํจํ์์ต๋๋ค.");
alert(JSON.stringify(error));
});
},
}
index.init();
detail.jsp์์ ์ญ์ ๋ฒํผ์ ๋ฃ์ด์ค id="btn-delete"๋ก ํจ์๋ฅผ ์๋์ํจ๋ค.
์ฌ๊ธฐ์ var id = $("#id").text();
๋ id๋ฅผ value๋ก ๋ฐ์์ค๋ ๊ฒ์ด ์๋ text๋ก ๋ฐ์์ค๊ธฐ ๋๋ฌธ์ ๋ค์ .text()๋ฅผ ๋ถ์ฌ์ผ ํ๋ค.
์ญ์ ์ด๋ฏ๋ก type="DELETE" ์ด๋ค!!
@DeleteMapping("/api/board/{id}")
public ResponseDto<Integer> deleteById(@PathVariable int id) {
boardService.๊ธ์ญ์ ํ๊ธฐ(id);
return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);
}
@DeleteMapping์ ์ฌ์ฉํ์ฌ ์ฃผ์๋ฅผ ๋งคํํ๊ณ , boardService์ ๊ธ์ญ์ ํ๊ธฐ ๋ฉ์๋๋ฅผ ํธ์ถํ๋ค.
@Transactional
public void ๊ธ์ญ์ ํ๊ธฐ(int id) {
System.out.println("๊ธ์ญ์ ํ๊ธฐ : "+id);
boardRepository.deleteById(id);
}
์ฌ๊ธฐ์ ํธ๋์ญ์
์ด๋
ธํ
์ด์
์ ๊ฑธ์ด์ผ ํ๋ค.
C, U, D ๊ธฐ๋ฅ์ ๋ฐ์ดํฐ๊ฐ ๋ณ๊ฒฝ๋๊ธฐ ๋๋ฌธ์ด๋ค.
์ฆ, ํธ๋์ญ์
์ด ์ข
๋ฃ๋๋ฉด ์ปค๋ฐ๋๊ณ ๋ณ๊ฒฝ์ด ๊ฐ์ง๋์ด ์์์ฑ ์ปจํ
์คํธ๊ฐ ์ค์ DB๋ก flush ๋๋ค.
์ฌ๊ธฐ ์ฐธ๊ณ