danDevlog

Spring - 13 (댓글 기능 - 페이징) 본문

Spring 게시판 만들기

Spring - 13 (댓글 기능 - 페이징)

단데기이 2022. 4. 25. 17:26
728x90

이제 댓글도 게시물처럼 페이징 작업을 해본다.

 

기존의 ReplyMapper.xml 에서 getListWithPaging 을 수정한다.

  		<!-- 검색이 빠진 페이징 처리와 같다. -->
  		<select id="getListWithPaging" resultType="kr.icia.domain.ReplyVO">
  			select rno, bno, reply, replyer, replydate, updatedate
  			from 
  			<![CDATA[
  			(select /*+INDEX(tbl_reply idx_reply) */
  			rownum rn, rno, bno, reply, replyer, replyDate, updatedate
  			from tbl_reply
  			where bno=#{bno}
  			and rno > 0
  			and rownum <= #{cri.pageNum} * #{cri.amount}
  			order by rno
  			) where rn > (#{cri.pageNum}-1) * #{cri.amount}
  			]]>
  		</select>

추가로 게시물별 총 댓글 개수를 파악하기위한 쿼리를 작성한다.

  		<!-- 게시물별 댓글 총갯수 리턴 -->
  		<select id="getCountByBno" resultType="int">
  			select count(rno) from tbl_reply where bno=#{bno}
  		</select>

 

ReplyMapper 인터페이스에 메소드를 추가한다.

// 게시물별 댓글 총갯수 파악.
	public int getCountByBno(Long bno);

 

domain패키지에 ReplyPageDTD 클래스를 생성한다.

import java.util.List;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;


// @Getter 위치 중요 : 초기화후 호출해야한다. 생략하면 호출하고 초기황 하여 오류 가 발생
@Data
@AllArgsConstructor
@Getter
public class ReplyPageDTO {
	private int replyTotalCnt; // 게시물별 덧글의 총 갯수.
	private List<ReplyVO> list; // 덧글의 목록
}

 

ReplyService 인터페이스에 메소드 원형을 추가한다.

	// 덧글의 목록과 게시물의 갯수.
	public ReplyPageDTO getListPage(Criteria cri, Long bno);

 

ReplyServiceImpl에 메소드를 구현한다.

	@Override
	public ReplyPageDTO getListPage(Criteria cri, Long bno) {
		return new ReplyPageDTO(mapper.getCountByBno(bno)
				, mapper.getListWithPaging(cri, bno));
		// 각각의 매퍼를 이용하여 덧글의 갯수와 덧글의 목록 추출.
		// ReplyPageDTO(게시물별 덧글 총갯수, 게시물별 10개씩 덧글 목록
	}

 

ReplyController의 getList 메소드를 수정한다.

	@GetMapping(value = "/pages/{bno}/{page}", produces = {
			MediaType.APPLICATION_JSON_VALUE })
	public ResponseEntity<ReplyPageDTO> getList(@PathVariable("page") int page
			, @PathVariable("bno") Long bno) {
		// @PathVariable : url로 넘겨받은 값 이용
		log.info("getList.....");
		Criteria cri = new Criteria(page , 10);
		log.info(cri);

		return new ResponseEntity<>(service.getListPage(cri, bno), HttpStatus.OK);
		// T<List<ReplyVO>> t = new T<>();
		// 댓글 목록을 출ㄹ력하고, 정상 처리 상태를 리턴
	}

ResponseEntity 반환 타입부분을 수정하였고,

return에서 servie.getListPage로 변경하였다.

 

reply.js에서 getList를 수정한다.

     // 댓글 목록 가져오기
     function getList(param, callback, error) {
             console.log("getlist....");
             var bno = param.bno;
             var page = param.page || 1; // 2개 갑중 하나로 변수 초기화
             // 페이지 번호가 있으면 페이지 번호 전달 아니면 1전달.
             $.getJSON("/replies/pages/" + bno + "/" + page,
                 function(data) {
                     if(callback) {
                          callback(data.replyTotalCnt, data.list);
                     }
                 }).fail(function(xhr, status, err){
                     // xhr : xml http request의 약자.
                     // 현재는 사용되지 않고, 형식만 맞춰줌.
                     if(error) {
                         error(er);
                     }
                 })
        } // 덧글 목록 가져오기 끝.

callback쪽을 보면 data.replyTotalCnt, data.list로 변경하면서 게시물 댓글의 합을 보내준다.

 

 

get.jsp에서 showList 메소드에 코드를 추가한다.

		function showList(page){
			replyService.getList(
					{
						bno : bnoValue,
						page : page || 1
					},
					// 익명함수 : 이름이 없으며 즉시 실행
					function(replyTotalCnt, list) {
						console.log("replyTotalCnt : " + replyTotalCnt);
						
						if(page == -1){
							// 페이지 번호가 음수 값 이라면,
							
							PageNum = Math.ceil(replyTotalCnt / 10.0);
							// 덧글의 마지막 페이지 구하기.
							
							showList(pageNum);
							// 덧글 목록 새로고침(갱신)
							
							return;
						}
						
						var str = "";
						
						if (list ==null || list.length == 0 ){
							replyUL.html("");
							return;
						} // 목록이 없을때 처리 끝.
						
						for (var i = 0, len = list.length || 0; i<len; i++){
							str += "<li class='left ";
							str += "clearfix' data-rno='";
							str += list[i].rno+"'>";
							str += "<div><div class='header' ";
							str += "><strong class='";
							str += "primart-font'>";
							str += list[i].replyer+ "</strong>";
							str += "<small class='float-sm-right '>";
							str += replyService.displayTime(list[i].replyDate)
							+ "</small></div>";
							str += "<p>" + list[i].reply;
							str += "</p></div></li>";
						}
						replyUL.html(str); 
					}); // end
		} // end_showlist
		showList(1);
		// 덧글 목록 표시 끝

 

위의 게시물은 현재 댓글이 15개인데 작업을 한 결과 10개만 출력되는것을 볼 수 있다.

 

아직 쪽번호를 만들지 않았기때문에 나머지 5개는 아직 보이지 않는다.

Comments