detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp"%>
<div class="container">
<button class="btn btn-secondary" onclick="history.back()">돌아가기</button>
<c:if test="${board.user.id == principal.user.id}">
<!-- 글 작성자만 삭제가능 -->
<a href="/board/${board.id }/updateForm" class="btn btn-warning">수정</a>
<button id="btn-delete" class="btn btn-danger">삭제</button>
</c:if>
<br>
<br>
<div>
글 번호 : <span id="id"><i>${board.id } </i></span> 작성자 : <span><i>${board.user.userName } </i></span>
</div>
<br>
<div>
<h3>${ board.title }</h3>
</div>
<hr>
<div>
<div>${board.content }</div>
</div>
<hr>
</div>
<script src="/js/board.js"></script>
<%@ include file="../layout/footer.jsp"%>
BoardController.java
@GetMapping("/board/{id}/updateForm")
public String updateForm(@PathVariable int id, Model model) {
model.addAttribute("board", boardService.글상세보기(id));
return "board/updateForm";
}
updateForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="../layout/header.jsp"%>
<div class="container">
<form>
<input type="hidden" id="id" value="${board.id }">
<div class="form-group">
<label for="title">Title</label>
<input value="${board.title }" type="text" class="form-control" placeholder="Enter title" id="title">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea class="form-control summernote" rows="5" id="content">${board.content }</textarea>
</div>
</form>
<button id="btn-update" class="btn btn-primary">글수정완료</button>
</div>
<script>
$('.summernote').summernote({
tabsize: 2,
height: 300
});
</script>
<script src="/js/board.js"></script>
<%@ include file="../layout/footer.jsp"%>
board.js
let index = {
init: function() {
$("#btn-update").on("click", () => {
this.update();
});
}
, update: function() {
let id = $("#id").val();
let data = {
title: $("#title").val(),
content: $("#content").val(),
};
$.ajax({
type: "PUT",
url: "/api/board/" + id,
data: JSON.stringify(data),
contentType: "application/json; charset=UTF-8",
dataType: "json"
}).done(function(resp) {
alert("글수정이 완료되었습니다.");
console.log(resp)
location.href = "/board/" + id; // 글 수정이 완료되면 원래의 게시물로 돌아와야한다.
}).fail(function(error) {
alert(JSON.stringify(error));
});
}
}
index.init();
BoardApiController.java
@PutMapping("/api/board/{id}")
public ResponseDto<Integer> update(@PathVariable int id, @RequestBody Board board){
boardService.글수정하기(id, board);
return new ResponseDto<Integer>(HttpStatus.OK.value(),1);
}
BoardService.java
@Transactional
public void 글수정하기(int id, Board requestBoard) {
Board board = boardRepository.findById(id)
.orElseThrow(()->{
return new IllegalArgumentException("글 찾기 실패 : 아이디를 찾을 수 없습니다.");
}); // 영속화 완료
board.setTitle(requestBoard.getTitle());
board.setContent(requestBoard.getContent());
// 해당 함수로 종료시(Service가 종료될때) 트랜잭션이 종료됩니다. 이때 더티체킹 - 자동 업데이트가 됨. db flush
}