ReplySaveRequestDto.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ReplySaveRequestDto {
private int userId;
private int boardId;
private String content;
}
detail.jsp
<!-- 댓글 작성 영역 -->
<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="2"></textarea>
</div>
<div class="card-footer">
<button type="button" id="btn-reply-save" class="btn btn-primary">등록</button>
</div>
</form>
</div>
BoardApiController.java
@PostMapping("/api/board/{boardId}/reply")
public ResponseDto<Integer> replySave(@RequestBody ReplySaveRequestDto replySaveRequestDto) {
boardService.댓글쓰기(replySaveRequestDto);
return new ResponseDto<Integer>(HttpStatus.OK.value(), 1);
}
board.js
let index = {
init: function() {
$("#btn-reply-save").on("click", () => {
this.replySave();
});
}
, replySave: function() {
let data = {
userId: $("#userId").val(),
boardId: $("#boardId").val(),
content: $("#reply-content").val()
};
let boardId = $("#boardId").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("댓글 작성이 완료되었습니다.");
console.log(resp)
location.href = `/board/${data.boardId}`;
}).fail(function(error) {
alert(JSON.stringify(error));
});
}
}
index.init();
BoardService.java
@Service
public class BoardService {
@Autowired
private UserRepository userRepository;
@Autowired
private BoardRepository boardRepository;
@Autowired
private ReplyRepository replyRepository;
@Transactional
public void 댓글쓰기(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);
}
}