상세 컨텐츠

본문 제목

부트스트랩 페이징, 페이지네이션 (Bootstrap Pagination), 페이징 예제

Spring

by husks 2016. 7. 29. 11:13

본문

반응형

 

 

부트스트랩을 사용하실때 페이지처리 예제 입니다. (Spring으로 개발 되었습니다.)

 

 

 

소스를 기존에 사용하던 프로젝트에서 그대로 가져와서 좀 복잡한데 필요한 부분만 보시면 될듯 합니다.

 

 

 

중요 부분은 라인수를 적어 놓겠습니다.

 

 

 

그리고 css, js 파일 등은 아래 첨부 파일에서 다운 받으세요.

 

css.zip
다운로드
fonts.zip
다운로드
js.zip
다운로드

 

 

company.jsp

 

88~89 라인

138 라인

142~166 라인 (중요체크)

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %> <!DOCTYPE html> <html lang="ko"> 	<head> 		<meta charset="utf-8"> 		<meta http-equiv="X-UA-Compatible" content="IE=edge"/> 		<!-- meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"/ --> 		<meta name="viewport" content="width=device-width, initial-scale=1.0"> 		<title>정산 사이트</title> 		<link rel="shortcut icon" href="/resources/image/icon/favicon.ico"> 		<!-- Bootstrap --> 		<link href="/resources/bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css"/> 		 		<link rel="stylesheet" href="/resources/bootstrap/css/datepicker.min.css" /> 		 		<!-- jQuery (부트스트랩의 자바스크립트 플러그인을 위해 필요한) --> 		<script src="//code.jquery.com/jquery.js"></script> 		<!-- 모든 합쳐진 플러그인을 포함하거나 (아래) 필요한 각각의 파일들을 포함하세요 --> 		<script src="/resources/bootstrap/js/bootstrap.min.js"></script> 		<!-- Respond.js 으로 IE8 에서 반응형 기능을 활성화하세요 (https://github.com/scottjehl/Respond) --> 		<script src="/resources/bootstrap/js/respond.js"></script> 		<script src="/resources/bootstrap/js/jquery.number.min.js"></script> 		<script src="/resources/bootstrap/js/jssor.slider.mini.js"></script> 		 		<script src="/resources/bootstrap/js/bootstrap-datepicker.min.js"></script> 		 		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes, target-densitydpi=medium-dpi" > 		<!--[if lt IE 9]> 	      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> 	      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> 	    <![endif]--> 	</head> 	<style> 		.viewer { width:100%;}         .viewer img { max-width:100%; }         table.view { 		    table-layout: fixed; 		} 		.nav-pills > li.active > a, .nav-pills > li.active > a:focus { 			color: black; 			background-color: #47C83E; 		} 		 		.nav-pills > li.active > a:hover { 			background-color: #35B62C; 		       color:black; 		} 		.datePicker { 		    float: left; 		} 		 		hr { 		  -moz-border-bottom-colors: none; 		  -moz-border-image: none; 		  -moz-border-left-colors: none; 		  -moz-border-right-colors: none; 		  -moz-border-top-colors: none; 		  border-color: #EEEEEE -moz-use-text-color #FFFFFF; 		  border-style: solid none; 		  border-width: 2px 0; 		  margin: 18px 0; 		} 		 		@media (min-width: 1200px) { 		.container { 			max-width: 99.9%; 		} 		table td { 		text-align: center;    		} 		table th { 		   text-align: center;    		} 		.modal.modal-wide .modal-dialog { 		  width: 90%; 		} 	</style> 	<div class="container"> 		<body> 			<h3><Strong>페이징 예제</Strong></h3> 			<hr> 			<div class="panel panel-default"> 				<div class="panel-body"> 					<form class="form-inline" id="frmSearch" action="/contract/company"> 						<input type="hidden" name="init" value="${init}" /><!-- 초기페이지인지 검색후 페이지인지 구분 --> 						<input type="hidden" id="startPage" name="startPage" value=""><!-- 페이징을 위한 hidden타입 추가 --> 						<input type="hidden" id="visiblePages" name="visiblePages" value=""><!-- 페이징을 위한 hidden타입 추가 --> 						<div class="row"> 							<div class="col-md-2" style="text-align:center"> 								<h4><strong>검색어</strong></h4> 							</div> 							<div class="col-md-10"> 								<input type="text" class="form-control" name="searchWord" value="${searchWord}" maxlength="8"/> 							</div> 						</div> 					</form> 				</div> 			</div> 			<div class="row"> 				<div class="col-md-12" style="text-align:right"> 					<button class="btn btn-default" id="search">조회</button> 				</div> 			</div> 			<div class="row"> 				<div class="col-md-12" style="height:45px"></div> 			</div> 			<!-- 1.거래일자 보여주기 --> 			<div class="row"> 				<div class="col-md-12"> 					<div class="panel panel-default"> 						<!-- Default panel contents --> 						<div class="panel-heading"><span class="glyphicon glyphicon-list"></span>  							조회결과 						</div> 						<!-- Table --> 						<div class="table-responsive"> 							<table class="table table-bordered table-hover specialCollapse"> 								<thead> 									<tr> 										<th class="text-center">회사아이디</th> 										<th class="text-center">회사명</th> 									</tr> 								</thead> 								<tbody> 									<c:forEach var="companyResult" items="${companyList}" varStatus="status"> 										<tr> 											<td>${companyResult.company_id}</td> 											<td>${companyResult.company_name}</td> 										</tr> 									</c:forEach> 								</tbody> 							</table> 						</div>	 					</div> 					<div class="col-md-12" align="center"> 						<ul id="pagination" class="pagination"></ul><!-- 페이지네이션 --> 					</div> 				</div> 			</div> 			<script src="/resources/bootstrap/js/jquery.twbsPagination.js"></script> 			<script type="text/javascript"> 			$(document).ready(function() { 				 				$("#search").click(function(){ 					$("#frmSearch").submit(); 				}); 					 				var totalPages = ${totalPage};//전체 페이지 				var visiblePages = 10;//리스트 보여줄 페이지 				var startPage = ${startPage};//현재 페이지 				 				$('#pagination').twbsPagination({ 					totalPages: totalPages, 					visiblePages: visiblePages, 					startPage: startPage, 					onPageClick: function (event, page) { 						$('#startPage').val(page);//보고 싶은 페이지 						$('#visiblePages').val(visiblePages); 						$("#frmSearch").submit(); 					} 				}); 								 			}); 			</script> 		</body> 	</div> </html> 

 

TotalPage.java

 

package kr.co.myapp.util;  import java.math.BigDecimal;  import org.springframework.stereotype.Component;  @Component public class TotalPage { 	 	public BigDecimal getTotalPage(int totalCnt, int visiblePages){ 		BigDecimal decimal1 = new BigDecimal(totalCnt); 		BigDecimal decimal2 = new BigDecimal(visiblePages); 		BigDecimal tatalPage = decimal1.divide(decimal2, 0, BigDecimal.ROUND_UP); 		 		return tatalPage; 	}  }  

 

 

PageableUtil.java

 

package kr.co.myapp.util;  import java.util.HashMap; import java.util.Map;  import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Component;  @Component public class PageableUtil { 	 	public Map<String, Object> getRowBounds(int startPage, int visiblePages){ 		 		if(startPage==1){ 			startPage = 0; 		}else{ 			startPage = (startPage-1)*visiblePages; 		} 		Map<String, Object> pageable = new HashMap<String, Object>(); 		 		pageable.put("start", startPage); 		pageable.put("end", visiblePages); 		 		return pageable; 	}  } 

 

 

ContractController.java

 

package kr.co.myapp.contract.controller;  import java.util.HashMap; import java.util.Map;  import kr.co.myapp.contract.service.ContractService; import kr.co.myapp.util.TotalPage;  import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam;  @Controller public class ContractController {  	@Autowired 	ContractService contractService;  	@Autowired 	private TotalPage totalPage; 	  	@RequestMapping(value = "/contract/company", method = RequestMethod.GET) 	public String company(@RequestParam Map<String, String> paramMap, Model model) {  		//null처리 및 기본값 셋팅 및 초기화 		String strStartPage = paramMap.get("startPage"); 		String strVisiblePages = paramMap.get("visiblePages");  		int startPage = 1; 		int visiblePages = 10;  		if(strStartPage != null && !strStartPage.equals("")){ 			startPage = Integer.parseInt(strStartPage); 		} 		if(strVisiblePages != null && !strVisiblePages.equals("")){ 			visiblePages = Integer.parseInt(strVisiblePages); 		}  		model.addAttribute("startPage", startPage);//현재 페이지 		model.addAttribute("totalPage", 1);//전체 게시물  		//처음 호출이 아니라면 		if(paramMap.get("init") != null){  			Map<String, Object> searchMap = new HashMap<String, Object>();  			String searchWord = paramMap.get("searchWord");  			//검색조건을 셋팅 			searchMap.put("searchWord", searchWord);  			//전체 게시물수 가져오기 			int totalCnt = contractService.getCompanyCnt(searchMap);  			model.addAttribute("init","N"); 			model.addAttribute("searchWord",searchWord);  			model.addAttribute("totalCnt", totalCnt);//전체 게시물 			model.addAttribute("totalPage", totalPage.getTotalPage(totalCnt, visiblePages));//전체 페이지 			model.addAttribute("companyList", contractService.getCompanyList(searchMap, startPage,  visiblePages));//검색  		}  		return "/contract/company"; 	}  } 

 

 

ContractDaoImpl.java (ContractService.java, ContractServiceImpl.java, ContractDaojava 는 생략하였습니다.)

 

package kr.co.myapp.contract.dao.impl;  import java.util.List; import java.util.Map;  import kr.co.myapp.contract.dao.ContractDao; import kr.co.myapp.contract.domain.Company; import kr.co.myapp.util.PageableUtil;  import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository;  @Repository("contractDao") public class ContractDaoImpl implements ContractDao{  	@Autowired 	private SqlSession sqlSession;  	@Autowired 	private PageableUtil pageableUtil;  	public void setSqlSession(SqlSession sqlSession){ 		this.sqlSession = sqlSession; 	}  	@Override 	public int getCompanyCnt(Map<String, Object> paramMap) {  		return sqlSession.selectOne("selectCompanyCnt", paramMap); 	}  	@Override 	public List<Company> getCompanyList(Map<String, Object> paramMap, int startPage, int visiblePages) {  		//페이징을 위한 limit 조건을 추가 		Map<String, Object> tmpSearchMap = pageableUtil.getRowBounds(startPage, visiblePages);  		paramMap.put("start", tmpSearchMap.get("start")); 		paramMap.put("end", tmpSearchMap.get("end"));  		return sqlSession.selectList("selectCompanyList", paramMap); 	}  } 

 

 

contract.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.myapp.contract.dao.ContractDao"> 	<select id="selectCompanyList" resultType="kr.co.myapp.contract.domain.Company" parameterType="java.util.HashMap"> 	    select 			company_id, 		    company_name 		from 			company 		<where> 			<if test='searchWord !=null and !searchWord.equals("")'>			 				and company_id = #{searchWord} 			</if> 		</where> 		order by company_id 		limit #{start}, #{end} 	</select> 	<select id="selectCompanyCnt" resultType="int"> 	    select 			count(company_id) company_cnt 		from 			company 		<where> 			<if test='searchWord !=null and !searchWord.equals("")'>			 				and company_id = #{searchWord} 			</if> 		</where> 	</select> </mapper> 

 

jsp 정리를 못해서 약간 복잡하고 나머지는 간단해서 천천히 보시면 이해가 되실것 같습니다.

 

참고: https://github.com/esimakin/twbs-pagination, http://esimakin.github.io/twbs-pagination/

 

반응형

관련글 더보기

댓글 영역