Hello

70. 댓글 작성하기

by 볼빵빵오춘기

Board

댓글이 작성된 순서 내림차순으로 정렬되서 가져와야하기때문이다.

@OrderBy("id desc")
@JsonIgnoreProperties({"board"})
@OneToMany(mappedBy = "board",fetch = FetchType.EAGER,cascade = CascadeType.REMOVE) // mappedBy 연관관계의 주인이 아니다.
private List<Reply> replys;

 

board.js

  • replySave() 함수를 작성하면 되는데 가져올 때 해당 Board의 원글의 정보도 알아야한다. (몇 번째 원글인지)
  • 따라서 detail.jsp 수정하여 해당 번호를 알 수 있도록 하자.
$("#btn-reply-save").on("click",()=>{
this.replySave();
});

 

detail.jsp

<div class="card">
<form>
<input type="hidden" id="boardId" value="${board.id}">
<div class="card-body">
<textarea id="reply-content" rows="2" class="form-control"></textarea>
</div>
<div class="card-footer">
<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
</div>
</form>
</div>

 

board.js

주의! 따옴표(’) x , 백틱(`) o

백틱을 사용하는 이유는 url 뒷부분의 게시물번호를 동적으로 받기 위해서이다.

replySave: function () {
let data = {
boardId : $("#boardId").val(),
content: $("#reply-content").val(),
};
$.ajax({
type: "POST",
url: `/api/board/${data.boardId}/reply`, // 참고로 여기서 따옴표가 아니라 백틱이다!
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done(function (resp) {
alert("댓글작성이 완료되었습니다.");
location.href = `/board/${data.boardId}`;
}).fail(function (error) {
alert(JSON.stringify(error));
});
},

 

BoardApiController

@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replaySave(@PathVariable int boardId,@RequestBody Reply reply, @AuthenticationPrincipal PrincipalDetail principal){
boardService.댓글쓰기(principal.getUser(),boardId,reply);
return new ResponseDto<Integer>(HttpStatus.OK.value(),1);
}

 

BoardService

@Autowired
private ReplyRepository replyRepository;
@Transactional
public void 댓글쓰기(User user, int boardId, Reply requestReply){
Board board= boardRepository.findById(boardId).orElseThrow(()->{
return new IllegalArgumentException("댓글 찾기 실패 : 게시글 id를 찾을 수 없습니다.");
});
requestReply.setUser(user);
requestReply.setBoard(board);
replyRepository.save(requestReply);
}
블로그의 프로필 사진

블로그의 정보

Hello 춘기's world

볼빵빵오춘기

활동하기