본문 바로가기
728x90
반응형

 VS Code 에서 바로복사하면 예쁘게해주는지 이제 처음 알았음.. 코드블럭 안쓸래 이제

 

PostController 내용 추가

 

    @Autowired
    CommentService commentService;
    @GetMapping("/Content")
    public ModelAndView viewPost(HttpServletRequest request) {
        String num = request.getParameter("num");
        Post post = postService.getPost(num);

        mav.setViewName("Post");
        mav.addObject("post", post);
       
        List<Comment> commentList = commentService.selectCommentByPostId(num);
        mav.addObject("commentList", commentList);

        System.out.println(post.getContents());
        mav.addObject("status", "0");

        return mav;
    }

 

Autowired 에 댓글 서비스 추가해주고,

게시글을 보여주는 Content Method 에 commentList 를 받아서 넘길수있게 바꿔주었다.

 

그리고 Post 객체도

 


@Data
public class Post {

    private String num;
    private String title;
    private String author;
    private String contents;
    private String date;
    private String commentNum;
}

 

가져올때 한번에 가져오기위해 commentNum 을 추가해줌. (insert 시에 사용하지않지만 이후 join 에서 한번에 담아와서 list 시에 댓글 수도 같이 뿌릴 수 있음)

 

 

PostService 에는 아래와 같이 추가하였다.

 

    @Autowired CommentDao commentDao;

 


    @Transactional
    public void deletePost(String num) throws IOException {
        commentDao.deleteCommentByPostId(num);
        postDao.deletePost(num);
    }

 

Transactional 로 중간에 SQL이 안되더라도 원자성을 유지할 수 있게끔 해준다.

우선 comment를 지우고 이후 post를 지우게 해뒀음.

 

이후 mapper-post.xml 도 수정해준다.


<select id="selectTotalList" parameterType="int" resultType="com.example.post.model.Post">
  SELECT t.*, c.commentNum
    FROM TEST1 t
    LEFT JOIN (
      SELECT postid, COUNT(*) AS commentNum
      FROM COMMENTS1
      GROUP BY postid
    ) c ON t.num = c.postid
  ORDER BY t.num DESC
  OFFSET #{pageNum} ROWS FETCH NEXT 10 ROWS ONLY
</select>

 <select id="selectList" parameterType="map" resultType="com.example.post.model.Post">
  SELECT t.*, c.commentNum
    FROM TEST1 t
    LEFT JOIN (
      SELECT postid, COUNT(*) AS commentNum
      FROM COMMENTS1
      GROUP BY postid
    ) c ON t.num = c.postid
    <where>
        <if test="sp.startDate != null and !sp.startDate.isEmpty()">
            AND CONVERT(varchar, DATE, 23) BETWEEN #{sp.startDate} AND #{sp.endDate}
        </if>
        <if test="sp.searchWord != null and !sp.searchWord.isEmpty()">
            AND ${sp.searchType} LIKE CONCAT('%', #{sp.searchWord}, '%')
        </if>
    </where>
    ORDER BY num DESC
    OFFSET #{pageNum} ROWS FETCH NEXT 10 ROWS ONLY
</select>

 

list 출력시 아래처럼 댓글 수도 같이 표현하고싶어서 게시글 리스트를 가져오는 SQL에 comment 테이블을 join 하여 같이 가지고 오게끔 바꾸었다.

 

 

그럼 jsp 를 수정하여 표시할수 있게끔 해본다.

 

 

 

List.jsp 에 게시글 list 작성 jstl 부분에 commentNum 값을 추가한다.

<table>
    <tr>
        <td>게시글번호</td><td>제목</td><td>작성자</td><td>날짜</td> <!-- 5개 -->
    </tr>
    <c:forEach items="${list}" var="post">
        <tr>
        <td>${post.num}</td><td><a href="${pageContext.request.contextPath}/Content?num=${post.num}">${post.title}
            [${post.commentNum}]</a></td><td>${post.author}</td><td>${post.date}</td>
        </tr>
    </c:forEach>
    </tr>
</table>

 

 

그리고 Post.jsp 에 댓글 작성 및 출력부분을 추가한다.

status==0  은 조회화면일 때를 나타냄 ( 수정일때 덧글내용이 나오면 안되니)

 

<c:choose>
    <c:when test="${status == 0}">
    <table>

    <c:forEach items="${commentList}" var="comment">
        <tr>
            <td>${comment.author}</td>
            <td>${comment.contents}</td>
            <td>${comment.date}</td>
            <td><a href="${pageContext.request.contextPath}/Comment/Delete?commentId=${comment.commentId}&postId=${post.num}">삭제</td>
        </tr>
    </c:forEach>
    </table>
    <form action="${pageContext.request.contextPath}/Comment/Write?num=${post.num}" method="post" accept-charset="utf-8">
        <input type="text" id="author" name="author" placeholder="작성자">
        <input type="text" id="contents" name="contents" placeholder="내용">
        <input type="hidden" id="postId" name="postId" value="${post.num}">
        <input type="submit" value="등록">
    </form>
    </c:when>
</c:choose>

 

 

 

내용도 대충이고 ui 도 대충이지만 아무튼 기능은 되니 우선 통과..

 

일단 댓글기능까지 완료하였다.

이후 JavaScript 나 비동기 통신을 활용한 것으로 바꿀지 모르겠지만 일단 여기까지

728x90
반응형

한걸음 한걸음

개인적인 기록