<!--id값 주기-->
<textarea id="reply-content" class="form-control" rows="1"></textarea>
<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
let index = {
$("#btn-reply-save").on("click", ()=>{
this.replySave();
});
},
replySave: function() {
let data = {
userId: $("#userId").val(),
boardId: $("#boardId").val(),
content: $("#reply-content").val()
};
console.log(data);
$.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));
});
},
//인터페이스생성
public interface ReplyRepository extends JpaRepository<Reply,Integer> {
}
서비스단과 컨트롤러에 한번에 넘기기 위해 생성
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReplySaveRequestDto {
private int userId; //유저아이디
private int boardId; //보드아이디
private String content; //댓글내용
}
//생성자 주입
private final ReplyRepository replyRepository;
private final UserRepository userRepository;
//댓글 등록
@Transactional
public void replyForm(ReplySaveRequestDto replySaveRequestDto) {
User user = userRepository.findById(replySaveRequestDto.getUserId()).orElseThrow(()->{
return new IllegalArgumentException("댓글쓰기 실패: 유저Id를 찾을 수 없습니다.");
});// 영속화 완료
Board board = boardRepository.findById(replySaveRequestDto.getBoardId()).orElseThrow(()->{
return new IllegalArgumentException("댓글쓰기 실패: 게시글Id를 찾을 수 없습니다.");
});// 영속화 완료
Reply reply = Reply.builder()
.user(user)
.board(board)
.content(replySaveRequestDto.getContent())
.build();
replyRepository.save(reply);
}
@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto ){
boardService.replyForm(replySaveRequestDto);
return new ResponseDto<Integer>(HttpStatus.OK.value(),1);
}
<!-- 댓글 창 만들기 -->
<div class="card">
<form>
<input type="hidden" id="userId" value="${principal.user.id}" /> <input
type="hidden" id="boardId" value="${board.id}" />
<div class="card-body">
<textarea id="reply-content" class="form-control" rows="1"></textarea>
</div>
<div class="card-footer">
<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
</div>
</form>
</div>
<br />
<div class="card">
<div class="card-header">댓글 리스트</div>
<ul id="comment--box" class="list-group">
<c:forEach var="reply" items="${board.reply}">
<li id="comment--1"
class="list-group-item d-flex justify-content-between">
<div>${reply.content }</div>
<div class="d-flex">
<div class="">작성자 ${reply.user.username}</div>
<button type="button" onClick="index.replyDelete(${board.id}, ${reply.id })" class="badge">삭제</button>
</div>
</li>
</c:forEach>
</ul>
</div>