CommentController.java
@Controller
@RequiredArgsConstructor
public class CommentController {
private final CommentService commentService;
// 댓글 등록
@PostMapping("/detail/{contentId}/comments")
public String addComment(
@PathVariable("contentId") Long contentId,
@RequestParam("comment") String comment,
@AuthenticationPrincipal MemberDetails memberDetails,
Model model) {
Member member = memberDetails.getMember();
commentService.addComment(contentId, comment, member);
model.addAttribute("message", "댓글이 등록되었습니다.");
return "redirect:/tourist/detail/" + contentId; // 댓글 등록 후 상세 페이지로 리다이렉트
}
// 댓글 수정
@PostMapping("/detail/{contentId}/comments/{commentId}/edit")
public String editComment(@PathVariable("contentId") Long contentId,
@PathVariable("commentId") Long commentId,
@RequestParam(required = false)
String updatedComment, Model model) {
commentService.updateCommentText(commentId, updatedComment);
model.addAttribute("message", "댓글이 수정되었습니다.");
return "redirect:/tourist/detail/" + contentId;
}
// 댓글 삭제
@PostMapping("/detail/{contentId}/comments/{commentId}/delete")
public String deleteComment(@PathVariable("contentId") Long contentId,
@PathVariable("commentId") Long commentId,
Model model) {
commentService.deleteComment(commentId);
model.addAttribute("message", "댓글이 삭제되었습니다.");
return "redirect:/tourist/detail/" + contentId; // 댓글 삭제 후 상세 페이지로 리다이렉트
}
}
CommentService.java
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class CommentService {
private final CommentRepository commentRepository;
// 댓글 추가
@Transactional
public void addComment(Long contentId, String commentText, Member member) {
Comment comment = new Comment();
comment.setContentId(contentId);
comment.setCommentText(commentText);
comment.setMember(member);
commentRepository.save(comment);
}
// 댓글 수정
@Transactional
public void updateCommentText(Long commentId, String updatedComment) {
commentRepository.updateCommentTextByCommentId(commentId, updatedComment);
}
// 댓글 삭제
@Transactional
public void deleteComment(Long commentId) {
commentRepository.deleteById(commentId);
}
// 해당 게시판의 댓글 리스트
public List<Comment> getCommentsByContentId(Long contentId) {
return commentRepository.findAllByContentId(contentId);
}
}
여기서 댓글을 등록한다.
이렇게 등록이 되고
수정 및 삭제도 가능하다.
여러개의 댓글 작성이 가능하다
이렇게 다른 사람의 댓글과 차별화 했다.