organize/프로젝트

justBoard15 댓글 구현(5) 댓글 페이지 처리

001cloudid 2024. 10. 20. 15:32
728x90

댓글 페이지 처리는 게시판 글 페이지 처리와 마찬가지로 PageDTO를 이용하면 될 것 같다.

그래서 Controller, Service, DAO에 pageDTO객체만 추가해 주면 될 것 같다는 생각이 들었다.

 

BoardController

	@GetMapping("/content")
	public String content(BoardDTO boardDTO, ReplyDTO replyDTO, PageDTO pageDTO,HttpServletRequest request, Model model) {
		System.out.println("BoardController Content()");
		boardDTO = boardService.getBoard(boardDTO); //글에 대한 정보
		boardService.readCount(boardDTO); //조회수
		
		//페이지
		int pageSize = 5; //화면에 보여줄 글의 개수
		String pageNum = request.getParameter("pageNum");
		if(pageNum ==null) {
			pageNum = "1";
		}
		int currentPage =Integer.parseInt(pageNum);	//int형 currentPage 변수명에 pageNum을 정수형으로 변경	
		
		//pageDTO에 저장
		pageDTO.setPageSize(pageSize);
		pageDTO.setPageNum(pageNum);
		pageDTO.setCurrentPage(currentPage);
		
		
	    List<ReplyDTO> replyList = boardService.getReplyList(boardDTO.getNo(), pageDTO); // 게시글 번호를 사용
	    
	    model.addAttribute("pageDTO",pageDTO);
	    model.addAttribute("boardDTO", boardDTO);
	    model.addAttribute("replyDTO", replyDTO);
	    model.addAttribute("replyList", replyList); // 댓글 리스트 추가
		return "board/content";
	}

 

BoardSerivce

	public List<ReplyDTO> getReplyList(int no, PageDTO pageDTO) {
		System.out.println("BoardService getReplyList()");
		return boardDAO.getReplyList(no, pageDTO);
	}

 

BoardDAO는 return값이 no과 pageDTO 두 개가 되어야하기 때문에 두 값을 Map을 사용하여 두 값을 변환할 수 있다.(검색을 통해 알아보았다.)

	public List<ReplyDTO> getReplyList(int no,PageDTO pageDTO) {
		System.out.println("BoardDAO getReplyList()");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("no", no);
		params.put("startRow", pageDTO.getStartRow());
		params.put("pageSize", pageDTO.getPageSize());
		return sqlSession.selectList(namespace+".getReplyList", params);
	}

 

여기서 Map을 배운지도, 사용한지도 오래되어 정리하고 지나가자.

Map이란(인터페이스)

  • 리스트나 배열처럼 순차적으로 해당 요소 값을 구하지 않고 키를 통해 값을 얻음
  • 키와 값을 쌍으로 저장하는 방식을 사용(키는 실질적인 값을 찾기 위한 이름의 역할)
  • 특징
    요소의 저장 순서를 유지하지 않음.
    키는 중복 불가, 값은 중복 가능.

Map 자주 사용하는 메소드

  • put
    Map에 데이터를 넣기, 추가
    /* 존재하는 경우 맵에서 키에 대한 매핑을 제거 */
    입력 시 지정한 타입에 맞게 값을 넣어줘야 함

    예시)
    Map<String, Object> param = new HashMap();
    param.put("번호",no);
    param.put("시작행", startRow);
    param.put("페이지크기", pageSize);

    MAP Table
    Key                   |  value
    번호                  |  no
    시작행              |  startRow
    페이지크기       |  pageSize

  • get
    원하는 데이터 출력
    /* 지정된 값을 이 맵의 지정된 키와 연결 */

    예시)
    System.out.println(map.get("번호")); //no

  • remove
    데이터 삭제

  • foreach문을 사용하여 Map 데이터 추출 (출처 : https://sin0824.tistory.com/13)
    -getKey : Map에 저장된 Key 출력
    -getValue : Map에 저장된 Value 출력

    예시)
    for(Entry<String, Object> entry : map.entrySet()){
        System.out.println(entry.getKey()); // 또는 System.out.println(entry.getValue());
    }
    //데이터 한 줄씩 출력
    for(Entry<string, object> entry : map.entrySet()){
        System.out.println(entry);
    }

화면으로 돌아가서 확인해 보니 다음과 같다.

화면에 보이는 댓글은 5개가 되는데 페이지가 증가하거나 하지 않음. 0을 클릭하면

이와 같은 오류가 발생한다.

 

startPage가 0으로 나타나는데 BoardDAO에 코드를 조금 수정해 보았다.

	public List<ReplyDTO> getReplyList(int no,PageDTO pageDTO) {
		System.out.println("BoardDAO getReplyList()");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("no", no);
//		params.put("startRow", pageDTO.getStartRow());
		params.put("startRow", (pageDTO.getCurrentPage()-1) * pageDTO.getPageSize());
		params.put("pageSize", pageDTO.getPageSize());
		return sqlSession.selectList(namespace+".getReplyList", params);
	}

 

그럼에도 변화가 없다. 댓글과 글의 페이지 처리를 별개로 관리하는 방식으로 해야 할 것 같다. 서로 로직이 비슷한 부분도 있지만 다른 부분도 있어 페이지 처리 로직이 다를 수 있기 때문이다. 따라서 ReplyPageDTO 클래스를 따로 분리해서 만들도록 해야겠다.

 

ReplyPageDTO

package com.mystory001.domain;

public class ReplyPageDTO {

    private int pageSize; //글의 개수
    private int currentPage; //현재 페이지
    private String pageNum;
    
    private int startRow; //시작하는 행 번호
    private int endRow; //끝나는 행 번호
    
    private int pageBlock; //한 화면에 보여 줄 페이지 개수
    private int startPage; //시작 페이지
    private int endPage; //끝 페이지
    
    private int count; //전체 글의 개수
    private int pageCount; //전체 페이지 개수
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public String getPageNum() {
		return pageNum;
	}
	public void setPageNum(String pageNum) {
		this.pageNum = pageNum;
	}
	public int getStartRow() {
		return startRow;
	}
	public void setStartRow(int startRow) {
		this.startRow = startRow;
	}
	public int getEndRow() {
		return endRow;
	}
	public void setEndRow(int endRow) {
		this.endRow = endRow;
	}
	public int getPageBlock() {
		return pageBlock;
	}
	public void setPageBlock(int pageBlock) {
		this.pageBlock = pageBlock;
	}
	public int getStartPage() {
		return startPage;
	}
	public void setStartPage(int startPage) {
		this.startPage = startPage;
	}
	public int getEndPage() {
		return endPage;
	}
	public void setEndPage(int endPage) {
		this.endPage = endPage;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getPageCount() {
		return pageCount;
	}
	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}
    
}

 

BoardController

	@GetMapping("/content")
	public String content(BoardDTO boardDTO, ReplyDTO replyDTO, ReplyPageDTO replyPageDTO,HttpServletRequest request, Model model) {
		System.out.println("BoardController Content()");
		boardDTO = boardService.getBoard(boardDTO); //글에 대한 정보
		boardService.readCount(boardDTO); //조회수
		
		//페이지 처리
		int pageSize = 5; //화면에 보여줄 글의 개수
		String pageNum = request.getParameter("pageNum");
		if(pageNum ==null) {
			pageNum = "1";
		}
		int currentPage =Integer.parseInt(pageNum);	//int형 currentPage 변수명에 pageNum을 정수형으로 변경	
		
		//replyPageDTO에 저장
		replyPageDTO.setPageSize(pageSize);
		replyPageDTO.setPageNum(pageNum);
		replyPageDTO.setCurrentPage(currentPage);
		
		//댓글 목록 조회
	    List<ReplyDTO> replyList = boardService.getReplyList(boardDTO.getNo(), replyPageDTO); // 게시글 번호를 사용
	    
	    //댓글 관련 설정
	    int count = boardService.getReplyCount(replyPageDTO); //전체 댓글의 개수 구하기
	    int pageBlock = 5; //한 화면에 보여줄 페이지 개수 설정
	    int startPage = (currentPage - 1) / pageBlock * pageBlock + 1; //한 화면에 보여 줄 시작 페이지
	    int endPage = startPage + pageBlock - 1; //한 화면에 보여 줄 끝 페이지
	    int pageCount = count / pageSize + (count % pageSize == 0? 0 : 1); //전체 페이지 개수
	    if(endPage > pageCount) {
	    	endPage = pageCount;
	    }
	    
	    //댓글 저장
	    replyPageDTO.setCount(count);
	    replyPageDTO.setPageBlock(pageBlock);
	    replyPageDTO.setStartPage(startPage);
	    replyPageDTO.setEndPage(endPage);
	    replyPageDTO.setPageCount(pageCount);
	    
	    model.addAttribute("replyPageDTO",replyPageDTO);
	    model.addAttribute("boardDTO", boardDTO);
	    model.addAttribute("replyDTO", replyDTO);
	    model.addAttribute("replyList", replyList); // 댓글 리스트 추가
		return "board/content";
	}

 

BoardSerivce

	public List<ReplyDTO> getReplyList(int no, ReplyPageDTO replyPageDTO) {
		System.out.println("BoardService getReplyList()");
		
		//시작하는 행 번호 구하기(currentPage,pageSize)
		int currentPage = replyPageDTO.getCurrentPage();
		int pageSize = replyPageDTO.getPageSize();
		int startRow = (currentPage - 1) * pageSize + 1;
		int endRow = startRow + pageSize - 1;
		
		replyPageDTO.setStartRow(startRow - 1);
		replyPageDTO.setEndRow(endRow);
		
		return boardDAO.getReplyList(no, replyPageDTO);
	}
	
	public int getReplyCount(ReplyPageDTO replyPageDTO) {
		System.out.println("BoardSerivce getReplyCount()");
		return boardDAO.getReplyCount(replyPageDTO);
	}

 

BoardDAO

	public List<ReplyDTO> getReplyList(int no,ReplyPageDTO replyPageDTO) {
		System.out.println("BoardDAO getReplyList()");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("no", no);
		params.put("startRow", replyPageDTO.getStartRow());
		params.put("pageSize", replyPageDTO.getPageSize());
		return sqlSession.selectList(namespace+".getReplyList", params);
	}

	public int getReplyCount(ReplyPageDTO replyPageDTO) {
		System.out.println("BoardDAO getReplyCount()");
		return sqlSession.selectOne(namespace+".getReplyCount", replyPageDTO);
	}

 

boardMapper

	<select id="getReplyList" resultType="com.mystory001.domain.ReplyDTO">
		select *
		from reply
		where `no` = #{no}
		order by replyWriteTime desc
		limit #{startRow}, #{pageSize}
	</select>
	
	<select id="getReplyCount" resultType="int">
		select count(*)
		from reply
		where `no` = #{no}
	</select>

 

문득 작성하고 나니 ReplyPageDTO에 no객체가 없어 문제가 생길 것이다. 또한 mapper에 join을 이용해서 sql을 작성해줘야 할 것 같다는 생각이 들었다.

 

글 목록에서 글을 클릭하면

내 예측이 맞았다. MyBatis가 ReplyPageDTO 클래스에서 no에 대한 객체에 대한 getter를 찾지 못했기 발생한 오류이다. 따라서 그에 맞는 수정

ReplyPageDTO

    private int boardNo; //게시글 번호
    
	public int getBoardNo() {
		return boardNo;
	}
	public void setBoardNo(int boardNo) {
		this.boardNo = boardNo;
	}

 

BoardDTO와 같이 no로 작성하려 했으나 변수명을 보고 어떤 것인지 한눈에 알 수 있어야 하기 때문에 조금 수정했다.

 

BoardController

	@GetMapping("/content")
	public String content(BoardDTO boardDTO, ReplyDTO replyDTO, ReplyPageDTO replyPageDTO,HttpServletRequest request, Model model) {
		System.out.println("BoardController Content()");
		boardDTO = boardService.getBoard(boardDTO); //글에 대한 정보
		boardService.readCount(boardDTO); //조회수
		
		//페이지 처리
		int pageSize = 5; //화면에 보여줄 글의 개수
		String pageNum = request.getParameter("pageNum");
		if(pageNum ==null) {
			pageNum = "1";
		}
		int currentPage =Integer.parseInt(pageNum);	//int형 currentPage 변수명에 pageNum을 정수형으로 변경	
		
		//replyPageDTO에 저장
		replyPageDTO.setPageSize(pageSize);
		replyPageDTO.setPageNum(pageNum);
		replyPageDTO.setCurrentPage(currentPage);
		replyPageDTO.setBoardNo(boardDTO.getNo()); //게시글 번호
		
		//댓글 목록 조회
	    List<ReplyDTO> replyList = boardService.getReplyList(replyPageDTO.getBoardNo(), replyPageDTO); // 게시글 번호를 사용
	    
	    //댓글 관련 설정
	    int count = boardService.getReplyCount(replyPageDTO.getBoardNo()); //전체 댓글의 개수 구하기
	    int pageBlock = 5; //한 화면에 보여줄 페이지 개수 설정
	    int startPage = (currentPage - 1) / pageBlock * pageBlock + 1; //한 화면에 보여 줄 시작 페이지
	    int endPage = startPage + pageBlock - 1; //한 화면에 보여 줄 끝 페이지
	    int pageCount = count / pageSize + (count % pageSize == 0? 0 : 1); //전체 페이지 개수
	    if(endPage > pageCount) {
	    	endPage = pageCount;
	    }
	    
	    //댓글 저장
	    replyPageDTO.setCount(count);
	    replyPageDTO.setPageBlock(pageBlock);
	    replyPageDTO.setStartPage(startPage);
	    replyPageDTO.setEndPage(endPage);
	    replyPageDTO.setPageCount(pageCount);
	    
	    model.addAttribute("replyPageDTO",replyPageDTO);
	    model.addAttribute("boardDTO", boardDTO);
	    model.addAttribute("replyDTO", replyDTO);
	    model.addAttribute("replyList", replyList); // 댓글 리스트 추가
		return "board/content";
	}

 

BoardService

	public List<ReplyDTO> getReplyList(int boardNo, ReplyPageDTO replyPageDTO) {
		System.out.println("BoardService getReplyList()");
		
		//시작하는 행 번호 구하기(currentPage,pageSize)
		int currentPage = replyPageDTO.getCurrentPage();
		int pageSize = replyPageDTO.getPageSize();
		int startRow = (currentPage - 1) * pageSize + 1;
		int endRow = startRow + pageSize - 1;
		
		replyPageDTO.setStartRow(startRow - 1);
		replyPageDTO.setEndRow(endRow);
		
		return boardDAO.getReplyList(boardNo, replyPageDTO);
	}
	
	public int getReplyCount(int boardNo) {
		System.out.println("BoardSerivce getReplyCount()");
		return boardDAO.getReplyCount(boardNo);
	}

 

BoardDAO

	public List<ReplyDTO> getReplyList(int boardNo,ReplyPageDTO replyPageDTO) {
		System.out.println("BoardDAO getReplyList()");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("boardNo", boardNo);
		params.put("startRow", replyPageDTO.getStartRow());
		params.put("pageSize", replyPageDTO.getPageSize());
		return sqlSession.selectList(namespace+".getReplyList", params);
	}

	public int getReplyCount(int boardNo) {
		System.out.println("BoardDAO getReplyCount()");
		return sqlSession.selectOne(namespace+".getReplyCount", boardNo);
	}

 

boardMapper

	<select id="getReplyList" resultType="com.mystory001.domain.ReplyDTO">
		select b.id, r.replyContent,r.replyWriteTime,r.`no`
		from board b join reply r on b.`no` = r.`no`
		where b.`no` = #{no}
		order by replyWriteTime desc
		limit #{startRow}, #{pageSize}
	</select>
	
	<select id="getReplyCount" resultType="int">
		select count(*)
		from reply
		where `no` = #{no}
	</select>

 

결과는?

로그인을 했는데 댓글을 확인할 수 없음.

로그인을 하지 않았을 때는 원하던 대로 구현되었음.

 

그래서 댓글 개수가 넘어오는지에 대해 찾아보니 0으로 뜸

 

댓글 개수가 0으로 나온다.

 

content.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>그냥 게시판</title>
</head>
<style>
.container{
	align-content : center;
	width: 1200px;
	height: 600px;
}
.content{
	width: 1000px;
	height: 600px;
}
</style>
<body>
<div class="container"> <%-- container 영역 div --%>

<jsp:include page="../inc/top.jsp" />

<jsp:include page="../inc/sidebar.jsp" />

<div class="content"> <%-- content영역 div --%>
<h1>글 읽기</h1>
<table >
<tr><td>글번호</td><td>${boardDTO.no}</td></tr>
<tr><td>글쓴이</td><td>${boardDTO.id}</td></tr>
<tr><td>조회수</td><td>${boardDTO.readcount}</td></tr>
<tr><td>작성일</td><td><fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${boardDTO.writetime}"/></td></tr>
<tr><td>글제목</td><td>${boardDTO.subject}</td></tr>
<tr><td>글내용</td><td>${boardDTO.content}</td></tr>
</table>
<div style="display: center">
<c:if test="${!empty sessionScope.id }">
	<c:if test="${sessionScope.id eq boardDTO.id}">
<a href="${pageContext.request.contextPath}/board/update?no=${boardDTO.no}"><input type="button" value="글 수정"></a> <a href="${pageContext.request.contextPath}/board/delete?no=${boardDTO.no}"><input type="button" value="글 삭제"></a>
	</c:if>
</c:if>
<a href="${pageContext.request.contextPath}/board/list"><input type="button" value="글 목록"></a>
</div>
<hr>
<c:if test="${empty sessionScope.id }">
<p><b>댓글은 회원만 작성 및 확인 할 수 있습니다. 확인을 위해서 회원 가입해주세요.</b></p><br>
</c:if>
<c:if test="${!empty sessionScope.id }">
댓글<br>
<form action="${pageContext.request.contextPath}/board/replyInsertPro" method="post">
<input type="hidden" name="no" value="${replyDTO.no }">
<input type="text" name="id" value="${sessionScope.id }" readonly="readonly"><br>
<textarea rows="5" cols="30" style="width: 792px; height: 35px" placeholder="내용을 작성해주세요." name="replyContent"></textarea><br>
<span style="float: right;"><input type="checkbox" name="replyHidden" value="true">비밀글 <input type="hidden" name="replyHidden" value="false"><input type="submit" value="작성"></span>
</form>
댓글 목록 <sub>비밀 댓글은 굵게 표시됩니다.</sub><br>
<c:if test="${empty replyList }">
작성된 댓글이 없습니다. 
</c:if>
<c:if test="${!empty replyList}">
    <table>
        <c:forEach var="replyDTO" items="${replyList}">
            <tr>
                <c:if test="${replyDTO.replyHidden == false}">
                    <td>작성자: ${replyDTO.id}</td>
                    <td>내용: ${replyDTO.replyContent}</td>
                    <td>작성시간: <fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${replyDTO.replyWriteTime}" /></td>
                </c:if>
                <c:if test="${replyDTO.replyHidden == true}">
                    <c:if test="${empty sessionScope.id}">
                        <td><b>권한이 없습니다.</b></td>
                    </c:if>
                    <c:if test="${sessionScope.id eq replyDTO.id or sessionScope.id eq boardDTO.id}">
                        <td><b>작성자: ${replyDTO.id}</b></td>
                        <td><b>내용: ${replyDTO.replyContent}</b></td>
                        <td><b>작성시간: <fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${replyDTO.replyWriteTime}" /></b></td>
                    </c:if>
                </c:if>
            </tr>
        </c:forEach>
    </table>
</c:if>
	<c:if test="${pageDTO.startPage > pageDTO.pageBlock}">
    	<a href="${pageContext.request.contextPath}/board/content?no=${boardDTO.no}&pageNum=${replyPageDTO.startPage - replyPageDTO.pageBlock}">Prev</a>
	</c:if>

	<c:forEach var="i" begin="${replyPageDTO.startPage}" end="${replyPageDTO.endPage}" step="1">
    	<a href="${pageContext.request.contextPath}/board/content?no=${boardDTO.no}&pageNum=${i}">${i}</a>
	</c:forEach>

	<c:if test="${replyPageDTO.endPage < replyPageDTO.pageCount}">
    	<a href="${pageContext.request.contextPath}/board/content?no=${boardDTO.no}&pageNum=${replyPageDTO.startPage + replyPageDTO.pageBlock}">Next</a>
	</c:if>
</c:if>
</div> <%-- content영역 div --%>
<jsp:include page="../inc/footer.jsp" />
</div> <%-- container 영역 div --%>
</body>
</html>

 

BoardController

	@GetMapping("/content")
	public String content(BoardDTO boardDTO, ReplyDTO replyDTO, ReplyPageDTO replyPageDTO,HttpServletRequest request, Model model) {
		System.out.println("BoardController Content()");
		boardDTO = boardService.getBoard(boardDTO); //글에 대한 정보
		boardService.readCount(boardDTO); //조회수
		
		//댓글 페이지 처리
		int pageSize = 5; //화면에 보여줄 글의 개수
		String pageNum = request.getParameter("pageNum");
		if(pageNum ==null) {
			pageNum = "1";
		}
		int currentPage =Integer.parseInt(pageNum);	//int형 currentPage 변수명에 pageNum을 정수형으로 변경	
		
		//replyPageDTO에 저장
		replyPageDTO.setPageSize(pageSize);
		replyPageDTO.setPageNum(pageNum);
		replyPageDTO.setCurrentPage(currentPage);
		replyPageDTO.setBoardNo(boardDTO.getNo()); //게시글 번호
		
		//댓글 목록 조회
		List<ReplyDTO> replyList = boardService.getReplyList(replyPageDTO.getBoardNo(), replyPageDTO); // 게시글 번호를 사용
	    
	    //댓글 관련 설정
	    int count = boardService.getReplyCount(replyPageDTO.getBoardNo()); //전체 댓글의 개수 구하기
	    int pageBlock = 5; //한 화면에 보여줄 페이지 개수 설정
	    int startPage = (currentPage - 1) / pageBlock * pageBlock + 1; //한 화면에 보여 줄 시작 페이지
	    int endPage = startPage + pageBlock - 1; //한 화면에 보여 줄 끝 페이지
	    int pageCount = count / pageSize + (count % pageSize == 0? 0 : 1); //전체 페이지 개수
	    if(endPage > pageCount) {
	    	endPage = pageCount;
	    }
	    
	    //댓글 저장
	    replyPageDTO.setCount(count);
	    replyPageDTO.setPageBlock(pageBlock);
	    replyPageDTO.setStartPage(startPage);
	    replyPageDTO.setEndPage(endPage);
	    replyPageDTO.setPageCount(pageCount);
	    
	    //모델에 데이터 추가
	    model.addAttribute("replyPageDTO",replyPageDTO);
	    model.addAttribute("boardDTO", boardDTO);
	    model.addAttribute("replyDTO", replyDTO);
	    model.addAttribute("replyList", replyList); // 댓글 리스트 추가
		return "board/content";
	}

 

BoardService

	public List<ReplyDTO> getReplyList(int boardNo, ReplyPageDTO replyPageDTO) {
		System.out.println("BoardService getReplyList()");
		
		
		//시작하는 행 번호 구하기(currentPage,pageSize)
		int currentPage = replyPageDTO.getCurrentPage();
		int pageSize = replyPageDTO.getPageSize();
		int startRow = (currentPage - 1) * pageSize + 1;
		int endRow = startRow + pageSize - 1;
		
		replyPageDTO.setStartRow(startRow - 1);
		replyPageDTO.setEndRow(endRow);
		
		return boardDAO.getReplyList(boardNo, replyPageDTO);
	}
	
	public int getReplyCount(int boardNo) {
		System.out.println("BoardSerivce getReplyCount()");
		return boardDAO.getReplyCount(boardNo);
	}

 

BoardDAO

	public List<ReplyDTO> getReplyList(int boardNo, ReplyPageDTO replyPageDTO) {
		System.out.println("BoardDAO getReplyList()");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("boardNo", boardNo);
		params.put("startRow", replyPageDTO.getStartRow());
		params.put("pageSize", replyPageDTO.getPageSize());
		return sqlSession.selectList(namespace+".getReplyList", params);
	}

	public int getReplyCount(int boardNo) {
		System.out.println("BoardDAO getReplyCount()");
		return sqlSession.selectOne(namespace+".getReplyCount", boardNo);
	}

 

boardMapper

	<select id="getReplyList" resultType="com.mystory001.domain.ReplyDTO">
		select b.id, r.replyContent,r.replyHidden, r.replyWriteTime,r.`no`
		from board b join reply r on b.`no` = r.`no`
		where b.`no` = #{no}
		order by replyWriteTime desc
		limit #{startRow}, #{pageSize}
	</select>
	
	<select id="getReplyCount" resultType="int">
		select count(*)
		from reply
		where `no` = #{no}
	</select>

 

이 지경이 되니까 생각된 것은 페이지마다 클래스를 분리하는 게 아니라 기능마다 클래스를 분리하는 것이 귀찮지만 나중에 더 유지보수하기에 편리해진다... 로직도 비슷하고 해서 따로 분리 안했는데 이렇게 되다보니 왜 분리해서 작업하는지 이해가 되는 부분이다. 하드코딩 된 것인지 모르겠는데 이쯤되니까 뭘 수정해야할지 머리가 돌아가지 않는다..

 

replyList가 null인 것 같은데 이를 가져와야할 듯하다. 글 번호를 가지고

수정해서 

BoardController

	@GetMapping("/content")
	public String content(BoardDTO boardDTO, ReplyDTO replyDTO, ReplyPageDTO replyPageDTO,HttpServletRequest request, Model model) {
		System.out.println("BoardController Content()");
		boardDTO = boardService.getBoard(boardDTO); //글에 대한 정보
		boardService.readCount(boardDTO); //조회수
		
		//댓글 페이지 처리
		int pageSize = 5; //화면에 보여줄 글의 개수
		String pageNum = request.getParameter("pageNum");
		if(pageNum ==null) {
			pageNum = "1";
		}
		int currentPage =Integer.parseInt(pageNum);	//int형 currentPage 변수명에 pageNum을 정수형으로 변경	
		
		//replyPageDTO에 저장
		replyPageDTO.setPageSize(pageSize);
		replyPageDTO.setPageNum(pageNum);
		replyPageDTO.setCurrentPage(currentPage);
		replyPageDTO.setBoardNo(boardDTO.getNo()); //게시글 번호
		
		//댓글 목록 조회
		List<ReplyDTO> replyList = boardService.getReplyList(replyPageDTO.getBoardNo(), replyPageDTO); // 게시글 번호를 사용
	    
	    //댓글 관련 설정
	    int count = boardService.getReplyCount(replyPageDTO.getBoardNo()); //전체 댓글의 개수 구하기
	    int pageBlock = 5; //한 화면에 보여줄 페이지 개수 설정
	    int startPage = (currentPage - 1) / pageBlock * pageBlock + 1; //한 화면에 보여 줄 시작 페이지
	    int endPage = startPage + pageBlock - 1; //한 화면에 보여 줄 끝 페이지
	    int pageCount = count / pageSize + (count % pageSize == 0? 0 : 1); //전체 페이지 개수
	    if(endPage > pageCount) {
	    	endPage = pageCount;
	    }
	    
	    //댓글 저장
	    replyPageDTO.setCount(count);
	    replyPageDTO.setPageBlock(pageBlock);
	    replyPageDTO.setStartPage(startPage);
	    replyPageDTO.setEndPage(endPage);
	    replyPageDTO.setPageCount(pageCount);
	    
	    //모델에 데이터 추가
	    model.addAttribute("replyPageDTO",replyPageDTO);
	    model.addAttribute("boardDTO", boardDTO);
	    model.addAttribute("replyDTO", replyDTO);
	    model.addAttribute("replyList", replyList); // 댓글 리스트 추가
		return "board/content";
	}

 

BoardService

	public List<ReplyDTO> getReplyList(int boardNo, ReplyPageDTO replyPageDTO) {
		System.out.println("BoardService getReplyList()");
		
		//시작하는 행 번호 구하기(currentPage,pageSize)
		int currentPage = replyPageDTO.getCurrentPage();
		int pageSize = replyPageDTO.getPageSize();
		int startRow = (currentPage - 1) * pageSize + 1;
		int endRow = startRow + pageSize - 1;
		
		replyPageDTO.setStartRow(startRow - 1);
		replyPageDTO.setEndRow(endRow);
		
		return boardDAO.getReplyList(boardNo, replyPageDTO);
	}
	
	public int getReplyCount(int boardNo) {
		System.out.println("BoardSerivce getReplyCount()");
		return boardDAO.getReplyCount(boardNo);
	}

 

BoardDAO

	public List<ReplyDTO> getReplyList(int boardNo, ReplyPageDTO replyPageDTO) {
		System.out.println("BoardDAO getReplyList()");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("boardNo", boardNo);
		params.put("startRow", replyPageDTO.getStartRow());
		params.put("pageSize", replyPageDTO.getPageSize());
		return sqlSession.selectList(namespace+".getReplyList", params);
	}

	public int getReplyCount(int boardNo) {
		System.out.println("BoardDAO getReplyCount()");
		return sqlSession.selectOne(namespace+".getReplyCount", boardNo);
	}

 

boardMapper

	<select id="getReplyList" resultType="com.mystory001.domain.ReplyDTO">
		select b.id, r.replyContent,r.replyHidden, r.replyWriteTime,r.`no`
		from board b join reply r on b.`no` = r.`no`
		where b.`no` = #{boardNo}
		order by r.replyWriteTime desc
		limit #{startRow}, #{pageSize}
	</select>
	
	<select id="getReplyCount" resultType="int">
		select count(*)
		from reply
		where `no` = #{no}
	</select>

 

content.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>그냥 게시판</title>
</head>
<style>
.container{
	align-content : center;
	width: 1200px;
	height: 600px;
}
.content{
	width: 1000px;
	height: 550px;
}
</style>
<body>
<div class="container"> <%-- container 영역 div --%>

<jsp:include page="../inc/top.jsp" />

<jsp:include page="../inc/sidebar.jsp" />

<div class="content"> <%-- content영역 div --%>
<h1>글 읽기</h1>
<table >
<tr><td>글번호</td><td>${boardDTO.no}</td></tr>
<tr><td>글쓴이</td><td>${boardDTO.id}</td></tr>
<tr><td>조회수</td><td>${boardDTO.readcount}</td></tr>
<tr><td>작성일</td><td><fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${boardDTO.writetime}"/></td></tr>
<tr><td>글제목</td><td>${boardDTO.subject}</td></tr>
<tr><td>글내용</td><td>${boardDTO.content}</td></tr>
</table>
<div style="display: center">
<c:if test="${!empty sessionScope.id }">
	<c:if test="${sessionScope.id eq boardDTO.id}">
<a href="${pageContext.request.contextPath}/board/update?no=${boardDTO.no}"><input type="button" value="글 수정"></a> <a href="${pageContext.request.contextPath}/board/delete?no=${boardDTO.no}"><input type="button" value="글 삭제"></a>
	</c:if>
</c:if>
<a href="${pageContext.request.contextPath}/board/list"><input type="button" value="글 목록"></a>
</div>
<hr>
<c:if test="${empty sessionScope.id }">
<p><b>댓글은 회원만 작성 및 확인 할 수 있습니다. 확인을 위해서 회원 가입해주세요.</b></p><br>
</c:if>
<c:if test="${!empty sessionScope.id }">
댓글<br>
<form action="${pageContext.request.contextPath}/board/replyInsertPro" method="post">
<input type="hidden" name="no" value="${replyDTO.no }">
<input type="text" name="id" value="${sessionScope.id }" readonly="readonly"><br>
<textarea rows="5" cols="30" style="width: 792px; height: 35px" placeholder="내용을 작성해주세요." name="replyContent"></textarea><br>
<span style="float: right;"><input type="checkbox" name="replyHidden" value="true">비밀글 <input type="hidden" name="replyHidden" value="false"><input type="submit" value="작성"></span>
</form>
댓글 목록 <sub>비밀 댓글은 굵게 표시됩니다.</sub><br>
<c:if test="${empty replyList }">
작성된 댓글이 없습니다. 
</c:if>
<c:if test="${!empty replyList}">
<%--     <c:out value="${replyList.size()}" /> 댓글 개수 --%>
    <table>
        <c:forEach var="replyDTO" items="${replyList}">
            <tr>
            <%-- replyHidden = 1이면 => 비밀글 => 굵게.  --%>
                     <c:if test="${replyDTO.replyHidden && replyDTO.id != sessionScope.id}">
                        <td style="width: 600px">작성자: ${replyDTO.id}</td>
                        <td style="width: 1000px">비밀글입니다.</td>
                        <td style="width: 600px">작성시간: <fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${replyDTO.replyWriteTime}" /></td>
                    </c:if>
                    <c:if test="${!replyDTO.replyHidden || replyDTO.id == sessionScope.id}">
                        <td style="width: 600px">작성자: ${replyDTO.id}</td>
                        <td style="width: 1000px"><b>내용: ${replyDTO.replyContent}</b></td>
                        <td style="width: 600px">작성시간: <fmt:formatDate pattern="yyyy-MM-dd hh:mm:ss" value="${replyDTO.replyWriteTime}" /></td>
                    </c:if>
                </tr>              
        </c:forEach>
    </table>
    
    <div style="float: right;">
    
    <c:if test="${pageDTO.startPage > pageDTO.pageBlock}">
    	<a href="${pageContext.request.contextPath}/board/content?no=${boardDTO.no}&pageNum=${replyPageDTO.startPage - replyPageDTO.pageBlock}">Prev</a>
	</c:if>

	<c:forEach var="i" begin="${replyPageDTO.startPage}" end="${replyPageDTO.endPage}" step="1">
    	<a href="${pageContext.request.contextPath}/board/content?no=${boardDTO.no}&pageNum=${i}">${i} </a>
	</c:forEach>

	<c:if test="${replyPageDTO.endPage < replyPageDTO.pageCount}">
    	<a href="${pageContext.request.contextPath}/board/content?no=${boardDTO.no}&pageNum=${replyPageDTO.startPage + replyPageDTO.pageBlock}">Next</a>
	</c:if>
    </div>

</c:if>
</c:if>
</div> <%-- content영역 div --%>
<jsp:include page="../inc/footer.jsp" />
</div> <%-- container 영역 div --%>
</body>
</html>

 

문제를 발견했다 댓글 작성자가 글을 쓴 작성자로 되는 문제가 있다.

댓글 작성자는 d2인데 글 작성자와 같게 되는 문제가 있다.

DB에는?

Controller에서 세션에 사용자 ID를 가져올 수 있도록 코드를 추가해줘야함

 

BoardController

	@PostMapping("/replyInsertPro")
	public String replyInsertPro(ReplyDTO replyDTO, Model model, HttpServletRequest request) {
		System.out.println("BoardController replyInsertPro()");
		
		//세션에 사용자ID 가져오기
		HttpSession session = request.getSession();
		String userID = (String)session.getAttribute("id");
		if(userID !=null ) {
			replyDTO.setId(userID); //댓글 작성자 ID 설정
		}
		
		boardService.replyInsert(replyDTO);
		return "redirect:/board/content?no="+replyDTO.getNo();
	}

 

코드를 수정하고 글쓴이와 댓글 작성자를 다르게 해서 댓글을 작성했다.

여기서는 작성자가 여전히 글쓴이와 동일함.

 

남은 작업 댓글작성자를 올바르게 표시 + 비밀글

 

 

728x90

'organize > 프로젝트' 카테고리의 다른 글

컬렉션 프레임워크(1) Map  (0) 2024.12.03
justBoard15 댓글 구현(6) 完  (0) 2024.11.11
justBoard14 댓글 구현(4)  (0) 2024.10.15
justBoard13 댓글 구현(3) 데이터  (0) 2024.10.13
justBoard12 댓글 구현(2) 화면  (1) 2024.10.12