카테고리 없음

[Spring Boot] Spring Boot JPA 프로젝트 - 댓글 기능 구현

코맹 2024. 6. 18. 15:33

 

HTML
<!doctype html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>게시판 상세</title>
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
</head>
<body>
    <!-- 게시글 영역 -->
    <h2 th:text="${board.title}"></h2>
    <div th:text="${board.content}"></div>

    <!-- 댓글 리스트 영역 -->
    <h5 th:text="|${#lists.size(board.replyList)}개의 댓글|"></h5>
    <div>
        <ul>
            <li th:each="reply : ${board.replyList}" th:text="${reply.content}"></li>
        </ul>
    </div>
    
    <!-- 답변기능 영역 -->
    <form th:action="@{|/reply/create/${board.bno}|}" method="post">
        <textarea name="content" id="content" rows="10"></textarea>
        <input type="submit" value="댓글등록">
    </form>
</body>
</html>​
  • 게시글 영역과 댓글 리스트 영역, 댓글 등록 창을 하나의 HTML 파일로 구성
  • #list.size( 이터러블객체)는 이터러블 객체의 사이즈를 반환하는 타임리프의 유틸리티

 

Controller
package com.eunji.backboard.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.eunji.backboard.entity.Board;
import com.eunji.backboard.service.BoardService;
import com.eunji.backboard.service.ReplyService;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

@RequestMapping("/reply")
@Controller
@RequiredArgsConstructor
@Log4j2
public class ReplyController {
  private final ReplyService replyService;
  private final BoardService boardService;

  @PostMapping("/create/{bno}")
  public String create(Model model, @PathVariable("bno") Long bno,
                       @RequestParam(value = "content") String content) throws Exception {
      Board board = this.boardService.getBoard(bno);    // 게시글 정보 가져오기
      this.replyService.setReply(board, content);

      log.info("[ReplyController] 댓글 저장 처리 완료");
      
      return String.format("redirect:/board/detail/%s", bno);
  }
}​
  • boardService.getBoard(bno) 메서드에서 select 해온 객체를 가지고 replyService.setReply(board, content); 메서드로 이동
Service
package com.eunji.backboard.service;

import java.time.LocalDateTime;

import org.springframework.stereotype.Service;

import com.eunji.backboard.entity.Board;
import com.eunji.backboard.entity.Reply;
import com.eunji.backboard.repository.ReplyRepository;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;

@Service
@RequiredArgsConstructor
@Log4j2
public class ReplyService {
  private final ReplyRepository replyRepository;

  public void setReply(Board board, String content) {
    //  builder를 사용한 방식
    Reply reply = Reply.builder().content(content).createDate(LocalDateTime.now()).board(board).build();
    log.info("댓글 객체 생성");

    this.replyRepository.save(reply);
    log.info("댓글 객체 저장");

  }
  
}​
  • builder를 사용해서 댓글 객체를 생성해서 저장해줌
결과

(CSS는 무시바람..😅)