본문 바로가기
코딩도전기/Spring

CODO Day46_Spring(Paging)

by 코도꼬마 2023. 4. 7.

Paging

  • 리스트의 수가 많아졌을 때 리스트를 한번에 보여줄 경우 데이터 양이 많아져 효율이 떨어짐
  • 이 경우 특정 개수만큼 페이지를 나누어 보여줄 수 있음

 

Paging 처리된 게시판 만들기

 

  • list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
	<meta charset="UTF-8">
	<title>Insert title here</title>
		<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
		<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
		<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>    
		<script src="resources/js/jquery.twbsPagination.js" type="text/javascript"></script>
		<style>
			b{
				color:red;
			}

			table{
				width:100%;
			}
			
			table, td, th{
				border : 1px solid;
				border-collapse : collapse;
				padding: 5px;
			}
			
			#paging{
				text-align: center;
			}
		</style>
</head>
<body>
	게시물 갯수 : 
	<select id="pagePerNum">
		<option value="5">5</option>
		<option value="10">10</option>
		<option value="15">15</option>
		<option value="20">20</option>
	</select>
	<table>
		<thead>
			<tr>
				<th>번호</th>					
				<th>제목</th>
				<th>작성자</th>
				<th>작성일</th>
				<th>조회</th>
			</tr>
		</thead>
		<tbody id="list">			
		<!-- 리스트가 출력될 영역 -->
		</tbody>
		<tr>
			<td colspan="6" id="paging">	
				<!-- 	플러그인 사용	(twbsPagination)	-->
				<div class="container">									
					<nav aria-label="Page navigation" style="text-align:center">
						<ul class="pagination" id="pagination"></ul>
					</nav>					
				</div>
			</td>
		</tr>
	</table>
</body>
<script>

	var showPage = 1;

	listCall(showPage);
	
	$('#pagePerNum').change(function(){
		listCall(showPage);
		//페이지 처리 부분이 이미 만들어져 있어서 pageperNum이 변경되면 수정이 안됨
		//pageTerNum이 변경되면 폼을 부수고 다시 만들어야 함
		$('#pagination').twbsPagination('destroy');
	});
	
	function listCall(page){
		$.ajax({
			type:'post',
			url:'list.ajax',
			data:{
				'page':page,
				'cnt':$('#pagePerNum').val()
			},
			dataType:'json',
			success:function(data){
				console.log(data);
				listPrint(data.list);
				
				//알고 있어야 할 것
				//1. 총 페이지 수 				
				//2. 현재 페이지
				
				//paging plugin
				$('#pagination').twbsPagination({
					startPage:data.currPage,  //시작페이지
					totalPages:data.pages, //총 페이지 수
					visiblePages:5,  //보여줄 페이지[1][2][3][4][5]
					onPageClick:function(event,page){ //페이지 클릭 시 동작되는 함수(콜백)
						console.log(page,showPage);
						if(page != showPage){
							showPage = page;
							listCall(page);
						}
					}
				});
				
			},
			error:function(e){
				console.log(e);
			}
		});
	}
	
	function listPrint(list){
		var content = '';
		//java.sql.Date는 js에서 읽지 못해 밀리세컨드로 반환\
		//해결방법 1. DTO에서 Date를 String으로 반환
		//해결방법 2. js에서 변환
		list.forEach(function(item,idx){
			content +='<tr>';
			content +='<td>'+item.idx+'</td>';
			content +='<td>'+item.subject+'</td>';
			content +='<td>'+item.user_name+'</td>';
			
			var date = new Date(item.reg_date);
			content +='<td>'+date.toLocaleDateString('ko-KR')+'</td>'; //toLocaleDateString 기본값 : US
			
			content +='<td>'+item.bHit+'</td>';
			content +='</tr>';
		});
		$('#list').empty();
		$('#list').append(content);
	}
</script>
</html>

 

  • jquery.twbsPagination.js
    • paging을 하기 위한 js 설정

jquery.twbsPagination.js
0.01MB

 

  • BoardController
package kr.co.gudi.controller;

import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import kr.co.gudi.service.BoardService;

@Controller
public class BoardController {
	
	@Autowired BoardService service;

	Logger logger = LoggerFactory.getLogger(getClass());
	
	@RequestMapping(value="/")
	public String main() {
		return "list";
	}
	
	@RequestMapping(value="/list.ajax", method=RequestMethod.POST)
	@ResponseBody
	public HashMap<String, Object> list(@RequestParam String page, @RequestParam String cnt){
		return service.list(Integer.parseInt(page),Integer.parseInt(cnt));
	}
}

 

  • BoardService
package kr.co.gudi.service;

import java.util.ArrayList;
import java.util.HashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import kr.co.gudi.dao.BoardDAO;
import kr.co.gudi.dto.BoardDTO;

@Service
public class BoardService {
	
	@Autowired BoardDAO dao;
	
	Logger logger = LoggerFactory.getLogger(getClass());

	public HashMap<String, Object> list(int page, int cnt) {
		
		logger.info(page+"페이지");
		logger.info("한 페이지에 "+cnt+"씩");

		HashMap<String, Object> map = new HashMap<String, Object>();
		
		// 1page = offset : 0
		// 2page = offset : 5
		// 3page = offset : 10
		int offset = (page-1)*cnt; 
		
		//만들 수 있는 총 페이지 수 = 전체 게시물 / 페이지 당 보여줄 수
		int total = dao.totalCount();
		logger.info("전체 게시물 수 : "+total);
		int range = total%cnt == 0 ? total/cnt : total/cnt+1;
		logger.info("총 페이지 수 : " + range);
		
		ArrayList<BoardDTO> list = dao.list(cnt,offset);
		
		page = page > range ? range : page;
		
		map.put("currPage", page);
		map.put("pages", range);
		map.put("list", list);
		
		return map;
	}

}

 

  • BoardDAO
package kr.co.gudi.dao;

import java.util.ArrayList;

import kr.co.gudi.dto.BoardDTO;

public interface BoardDAO {

	ArrayList<BoardDTO> list(int cnt, int offset);

	int totalCount();

}

 

  • BoardDTO
package kr.co.gudi.dto;

import java.sql.Date;

public class BoardDTO {

	private int idx;
	private String subject;
	private String content;
	private String user_name;
	private int bHit;
	private Date reg_date;
	
	public int getIdx() {
		return idx;
	}
	public void setIdx(int idx) {
		this.idx = idx;
	}
	public String getSubject() {
		return subject;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public int getbHit() {
		return bHit;
	}
	public void setbHit(int bHit) {
		this.bHit = bHit;
	}
	public Date getReg_date() {
		return reg_date;
	}
	public void setReg_date(Date reg_date) {
		this.reg_date = reg_date;
	}
	
}

 

  • board_mapper.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC   "-//mybatis.org//DTD Mapper 3.0//EN"
   "http://mybatis.org/dtd/mybatis-3-mapper.dtd"
>

<mapper namespace="kr.co.gudi.dao.BoardDAO">
   
   <select id="list" resultType="kr.co.gudi.dto.BoardDTO">
   		SELECT idx,subject,user_name,reg_date,bHit FROM bbs
   			ORDER BY idx DESC LIMIT #{param1} OFFSET #{param2}
   </select>
   
   <select id="totalCount" resultType="int">
   		SELECT COUNT(idx) FROM bbs
   </select>
   
</mapper>

 

 

'코딩도전기 > Spring' 카테고리의 다른 글

Transaction  (0) 2023.12.30
AOP - Proxy Pattern  (1) 2023.12.30
CODO Day45_Spring(AJAX)  (0) 2023.04.05
CODO Day44_Spring(PhotoBoard)  (0) 2023.04.04
CODO Day43_Spring(FileService)  (0) 2023.04.03