스프링 25강 - Paging처리

voilà!·2022년 2월 13일
0

JSP 스프링

목록 보기
25/31

list.jsp에 bootstrap 추가하기

1) 구글에 sb admin2 검색
https://startbootstrap.com/theme/sb-admin-2 들어가서 다운로드 클릭
압축풀고 webapp 폴더의 resources에 넣기

2) views 폴더에 aside.jsp, header.jsp, footer.jsp파일을 각각 만들어 처리하고, list.jsp의 <body>에 <jsp:include>의 page 속성을 사용하여 추가함

3) list.jsp의 경로 바꾸기
(1) src="vendor 검색
src="/resources/sbadmin2/vendor로 바꾸기
(2) src="js 검색
src="/resources/sbadmin2/js 로 바꾸기
(3) href="css 검색
href="/resources/sbadmin2/css로 바꾸기
(4) href="vendor 검색
href="/resources/sbadmin2/vendor로 바꾸기
(5) src="img 검색
href="/resources/sbadmin2/vendor/img로 바꾸기

Paging 처리용 클래스 생성

ArticlePage.java

package kr.or.ddit;

import java.util.List;

//페이징 처리를 위한 클래스
//게시글 데이터와 페이징 관련 정보를 담고 있음
public class ArticlePage {
	//페이징 관련 멤버변수
    //전체 글의 행의 수
    private int total;
    //현재 페이지 번호
    private int currentPage;
    //전체 페이지 개수
    private int totalPages;
    //시작 페이지 번호
    private int startPage;
    //종료 페이지 번호
    private int endPage;
    //페이징의 개수
    private int pagingCount;
    //게시글 데이터
    private List<LprodVO> content;
    
	//생성자
    //size : 한 화면에 보여질 행의 수
    public ArticlePage(int total, int currentPage, int size, int pagingCount, List<LprodVO> content) {
		super();
		this.total = total;
		this.currentPage = currentPage;
		this.content = content;
		this.pagingCount = pagingCount;
		//select 결과가 없다면..
		if(total == 0) {
			totalPages = 0;
			startPage = 0;
			endPage = 0;
        }else { //select 결과가 있을 때
        	//전체 페이지 개수 구하기(전체 글의 수/한 화면에 보여질 행의 수)
            //정수와 정수의 나눗셈 결과는 정수! 13 / 7 => 1
            totalPages = total / size;
            //보정해줘야 할 경우는? 15 / 7 = 2 경우 처럼 나머지가 0보다 클 때
        	if(total % size > 0){
            	totalPages++;
            }
            
			//startPage : 이전 [1] [2] [3] [4] [5] 다음    일 때 1을 의미
            //startPage 공식 : 현재 페이지 / 페이징의 개수 * 페이징의 개수 + 1 
            startPage = currentPage / pagingCount * pagingCount + 1;
			//보정해줘야 할 경우는? 5 / 5 * 5 + 1 => 6 경우처럼
			//				현재페이지  % 5 == 0 일 때  (5, 10, 15처럼)
			if(currentPage%pagingCount==0) {
				//startPage = startPage - 5(페이징의 개수);
				startPage -= pagingCount;
			//endPage : 이전 [1] [2] [3] [4] [5] 다음    일 때 5를 의미
			endPage = startPage + (pagingCount-1);
			//보정해줘야 할 경우는? endPage > totalPages 일 때 (ex 5 > 3)
			//					endPage를 totalPages로 바꿔줘야 함 (ex 5를 3으로 바꾸자!)
			if(endPage > totalPages) {
				endPage = totalPages;
			}
		}//end outer if
		
	}
	//전체 행의 수를 리턴
	//자바빈 클래스가 아니기 때문에 모든 멤버변수의 getter/setter메소드를 만들 필요는 없다.
	public int getTotal() {
		return this.total;
	}
	
	//select 결과가 없는가? true면 결과가 없다는 의미
	public boolean hasnoArticles() {
		return this.total == 0;
	}
	
	//select 결과가 있는가? true면 결과가 있다는 의미
	public boolean hasArticles() {
		return this.total > 0;
	}
	
	//현재 페이지 번호 리펀
	public int getCurrentPage() {
		return this.currentPage;
	}
	
	//전체 페이지의 개수 리턴
	public int getTotalPages() {
		return totalPages;
	}
	
	//데이터 VO List 리턴
	public List<LprodVO> getContent() {
		return this.content;
	}
	
	//목록 하단의 시작 번호를 리턴
	public int getStartPage() {
		return this.startPage;
	}
	
	//목록 하단의 종료 번호를 리턴
	public int getEndPage() {
		return this.endPage;
	}
	
}

컨트롤러에서 ArticlePage 객체 생성

LprodController.java

package kr.or.ddit;

import java.util.List;

@RequestMapping(value = "lprod")
@Controller
public class LprodController {
	private static final Logger logger = LoggerFactory.getLogger(LprodController.class);
    
    @Inject
    LprodService lprodService;
    
	//http://localhost:8090/lprod/list?currentPage=1 처럼 
	//@RequestParam으로 가져오는 파라미터는 String이 아닌 int, Map, VO로도 가능하다..
	//http://localhost:8090/lprod/list처럼 해당 요청 파라미터를 지정하지 않는 경우, defaultValue 속성에 지정한 문자열을 값으로 이용하게 됨(http://localhost:8090/lprod/list 처럼 currentPage의 값을 모를 때, null일 때)
    @RequestMapping(value = "/list")
    public String list(Model model, @RequestParam(defaultValue = "1") int currentPage) {
    //currentPage 출력
    logger.info("currentPage : " + currentPage);
    
    List<LprodVO> list = this.lprodService.list();
    
    //상품분류 별 거래처 목록 행의 수
    int total = this.lprodService.listCount();
    logger.info("total : " + total);
    
    //페이징 처리한 객체를 넣는다.
    model.addAttribute("list", new ArticlePage(total, currentPage, 7, 5, list));
    model.addAttribute("total", total);
    
    //forward
    return "lprod/list";
    }
    


}

JSP

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>상품분류 별 거래처 목록</title>

    <!-- Custom fonts for this template-->
    <link href="/resources/sbadmin2/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
    <link
        href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
        rel="stylesheet">

    <!-- Custom styles for this template-->
    <link href="/resources/sbadmin2/css/sb-admin-2.min.css" rel="stylesheet">

</head>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

        <!-- Sidebar -->
        <jsp:include page="../includes/aside.jsp"></jsp:include>
        <!-- End of Sidebar -->

        <!-- Content Wrapper -->
        <div id="content-wrapper" class="d-flex flex-column">

            <!-- Main Content -->
            <div id="content">

                <!-- Topbar -->
                <jsp:include page="../includes/header.jsp"></jsp:include>
                <!-- End of Topbar -->

                <!-- Begin Page Content 본문 시작 -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                    <h1 class="h3 mb-2 text-gray-800">상품분류 별 거래처 목록</h1>
                    <p class="mb-4">상품분류 별로 거래처의 목록을 화면에 보여줍니다.</p>

                    <!-- DataTales Example -->
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">DataTables Example</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <div id="dataTable_wrapper" class="dataTables_wrapper dt-bootstrap4"><div class="row"><div class="col-sm-12 col-md-6"><div class="dataTables_length" id="dataTable_length"><label>Show <select name="dataTable_length" aria-controls="dataTable" class="custom-select custom-select-sm form-control form-control-sm"><option value="10">10</option><option value="25">25</option><option value="50">50</option><option value="100">100</option></select> entries</label></div></div><div class="col-sm-12 col-md-6"><div id="dataTable_filter" class="dataTables_filter"><label>Search:<input type="search" class="form-control form-control-sm" placeholder="" aria-controls="dataTable"></label></div></div></div><div class="row"><div class="col-sm-12"><table class="table table-bordered dataTable" id="dataTable" width="100%" cellspacing="0" role="grid" aria-describedby="dataTable_info" style="width: 100%;">
                                    <thead>
                                    <tr role="row">
                                        <th class="sorting sorting_asc" tabindex="0" aria-controls="dataTable" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Name: activate to sort column descending" style="width: 50px;">번호</th>
                                        <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1" colspan="1" aria-label="Position: activate to sort column ascending" style="width: 200px;">상품분류코드</th>
                                        <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1" colspan="1" aria-label="Office: activate to sort column ascending">상품분류명</th>
                                        <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1" colspan="1" aria-label="Age: activate to sort column ascending" style="width: 200px;">거래처코드</th>
                                        <th class="sorting" tabindex="0" aria-controls="dataTable" rowspan="1" colspan="1" aria-label="Start date: activate to sort column ascending">거래처명</th>
                                    </tr>
                                    </thead>
                                    <tfoot>
                                     <tr>
                                     	<th rowspan="1" colspan="1">번호</th>
                                        <th rowspan="1" colspan="1">상품분류코드</th>
                                        <th rowspan="1" colspan="1">상품분류명</th>
                                        <th rowspan="1" colspan="1">거래처코드</th>
                                        <th rowspan="1" colspan="1">거래처명</th>
                                     </tr>
                                    </tfoot>
                                    <tbody>
                                    <c:set var="i" value="0"/>
                                    <c:forEach var="lprodVO" items="${list.content}">
                                    <c:forEach var="buyerVO" items="${lprodVO.buyerVO}">
                                    <c:set var="cnt" value="${i=i+1}" />
                                    <c:if test="${cnt%2==1}">
                                    <tr class="odd">
                                    </c:if>
                                    <c:if test="${cnt%2==0}">
                                    <tr class="even">
                                    </c:if>
                                            <td class="sorting_1">${cnt}</td>
                                            <td>${lprodVO.lprodGu}</td>
                                            <td>${lprodVO.lprodNm}</td>
                                            <td>${buyerVO.buyerId}</td>
                                            <td>${buyerVO.buyerName}</td>
                                     </tr>
                                     </c:forEach>
                                     </c:forEach>
                                     </tbody>
                                </table>
                                </div>
                                </div>
                                <div class="row">
                                <div class="col-sm-12 col-md-5">
                                <div class="dataTables_info" id="dataTable_info" role="status" aria-live="polite">
                                <!-- A*7-6 A*7 -->
                                Showing ${param.currentPage*7-6} to ${param.currentPage*7} of ${total} entries
                                </div>
                                </div>
                                <div class="col-sm-12 col-md-7">
                                <div class="dataTables_paginate paging_simple_numbers" id="dataTable_paginate">
                                <!-- 페이징 처리 시작 -->
                                <ul class="pagination">
                                <!-- Previous 시작 -->
	                                <li class="paginate_button page-item previous <c:if test='${list.startPage<6}'>disabled</c:if>" id="dataTable_previous"><a href="/lprod/list?currentPages=${list.startPage-5}" aria-controls="dataTable" data-dt-idx="0" tabindex="0" class="page-link">Previous</a></li>
                                <!-- Previous 끝 -->
                                <!-- Page번호 시작, 컨트롤러에서 list에 페이징 객체를 넣었으므로 list.변수명으로 불러옴 -->
                                <c:forEach var="pNo" begin="${list.startPage}" end="${list.endPage}" step="1">
	                                <li class="paginate_button page-item <c:if test='${param.currentPage eq pNo}'>active</c:if>"><a href="/lprod/list?currentPage=${pNo}" aria-controls="dataTable" data-dt-idx="1" tabindex="0" class="page-link">${pNo}</a></li>
                                </c:forEach>
                                <!-- Page번호 끝 -->
                                <!-- Next 시작 -->
	                                <li class="paginate_button page-item next<c:if test='${list.endPage>=list.totalPages}'>disabled</c:if>" id="dataTable_next"><a href="/lprod/list?currentPage=${list.startPage+5}" aria-controls="dataTable" data-dt-idx="7" tabindex="0" class="page-link">Next</a></li>
                                <!-- Next 끝 -->
	                            <!-- 페이징 처리 끝 -->
                                </ul></div></div></div></div>
                            </div>
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid 본문 끝-->

            </div>
            <!-- End of Main Content -->

            <!-- Footer -->
            <jsp:include page="../includes/footer.jsp"></jsp:include>
            <!-- End of Footer -->

        </div>
        <!-- End of Content Wrapper -->

    </div>
    <!-- End of Page Wrapper -->

    <!-- Scroll to Top Button-->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Logout Modal-->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                    <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="login.html">Logout</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <script src="/resources/sbadmin2/vendor/jquery/jquery.min.js"></script>
    <script src="/resources/sbadmin2/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

    <!-- Core plugin JavaScript-->
    <script src="/resources/sbadmin2/vendor/jquery-easing/jquery.easing.min.js"></script>

    <!-- Custom scripts for all pages-->
    <script src="/resources/sbadmin2/js/sb-admin-2.min.js"></script>

    <!-- Page level plugins -->
    <script src="/resources/sbadmin2/vendor/chart.js/Chart.min.js"></script>

    <!-- Page level custom scripts -->
    <script src="/resources/sbadmin2/js/demo/chart-area-demo.js"></script>
    <script src="/resources/sbadmin2/js/demo/chart-pie-demo.js"></script>

</body>

</html>

0개의 댓글