티스토리 뷰
참조
- http://blog.whitelife.co.kr/215
JSP에서 게시판을 만들때 등등 pagination을 해야할 때가 많다.
은근히 까다로운 부분이 많아서 만든 기회를 통해 정리를 해보고자 한다.
page가 변동될때마다 get방식으로 "page"라는 변수명으로 url에 전달해준다.
paging.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 | <p> public class Paging { private int pageSize; // 게시 글 수 private int firstPageNo; // 첫 번째 페이지 번호 private int prevPageNo; // 이전 페이지 번호 private int startPageNo; // 시작 페이지 (페이징 네비 기준) private int pageNo; // 페이지 번호 private int endPageNo; // 끝 페이지 (페이징 네비 기준) private int nextPageNo; // 다음 페이지 번호 private int finalPageNo; // 마지막 페이지 번호 private int totalCount; // 게시 글 전체 수 /** * @return the pageSize */ public int getPageSize() { return pageSize; } /** * @param pageSize the pageSize to set */ public void setPageSize( int pageSize) { this .pageSize = pageSize; } /** * @return the firstPageNo */ public int getFirstPageNo() { return firstPageNo; } /** * @param firstPageNo the firstPageNo to set */ public void setFirstPageNo( int firstPageNo) { this .firstPageNo = firstPageNo; } /** * @return the prevPageNo */ public int getPrevPageNo() { return prevPageNo; } /** * @param prevPageNo the prevPageNo to set */ public void setPrevPageNo( int prevPageNo) { this .prevPageNo = prevPageNo; } /** * @return the startPageNo */ public int getStartPageNo() { return startPageNo; } /** * @param startPageNo the startPageNo to set */ public void setStartPageNo( int startPageNo) { this .startPageNo = startPageNo; } /** * @return the pageNo */ public int getPageNo() { return pageNo; } /** * @param pageNo the pageNo to set */ public void setPageNo( int pageNo) { this .pageNo = pageNo; } /** * @return the endPageNo */ public int getEndPageNo() { return endPageNo; } /** * @param endPageNo the endPageNo to set */ public void setEndPageNo( int endPageNo) { this .endPageNo = endPageNo; } /** * @return the nextPageNo */ public int getNextPageNo() { return nextPageNo; } /** * @param nextPageNo the nextPageNo to set */ public void setNextPageNo( int nextPageNo) { this .nextPageNo = nextPageNo; } /** * @return the finalPageNo */ public int getFinalPageNo() { return finalPageNo; } /** * @param finalPageNo the finalPageNo to set */ public void setFinalPageNo( int finalPageNo) { this .finalPageNo = finalPageNo; } /** * @return the totalCount */ public int getTotalCount() { return totalCount; } /** * @param totalCount the totalCount to set */ public void setTotalCount( int totalCount) { this .totalCount = totalCount; this .makePaging(); } /** * 페이징 생성 */ private void makePaging() { if ( this .totalCount == 0 ) return ; // 게시 글 전체 수가 없는 경우 if ( this .pageNo == 0 ) this .setPageNo( 1 ); // 기본 값 설정 if ( this .pageSize == 0 ) this .setPageSize( 10 ); // 기본 값 설정 int finalPage = (totalCount + (pageSize - 1 )) / pageSize; // 마지막 페이지 if ( this .pageNo > finalPage) this .setPageNo(finalPage); // 기본 값 설정 if ( this .pageNo < 0 || this .pageNo > finalPage) this .pageNo = 1 ; // 현재 페이지 유효성 체크 boolean isNowFirst = pageNo == 1 ? true : false ; // 시작 페이지 (전체) boolean isNowFinal = pageNo == finalPage ? true : false ; // 마지막 페이지 (전체) int startPage = ((pageNo - 1 ) / 10 ) * 10 + 1 ; // 시작 페이지 (페이징 네비 기준) int endPage = startPage + 10 - 1 ; // 끝 페이지 (페이징 네비 기준) if (endPage > finalPage) { // [마지막 페이지 (페이징 네비 기준) > 마지막 페이지] 보다 큰 경우 endPage = finalPage; } this .setFirstPageNo( 1 ); // 첫 번째 페이지 번호 if (isNowFirst) { this .setPrevPageNo( 1 ); // 이전 페이지 번호 } else { this .setPrevPageNo(((pageNo - 1 ) < 1 ? 1 : (pageNo - 1 ))); // 이전 페이지 번호 } this .setStartPageNo(startPage); // 시작 페이지 (페이징 네비 기준) this .setEndPageNo(endPage); // 끝 페이지 (페이징 네비 기준) if (isNowFinal) { this .setNextPageNo(finalPage); // 다음 페이지 번호 } else { this .setNextPageNo(((pageNo + 1 ) > finalPage ? finalPage : (pageNo + 1 ))); // 다음 페이지 번호 } this .setFinalPageNo(finalPage); // 마지막 페이지 번호 } /*@Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); }*/ } </p> |
Paing.java 클래스를 통해서 페이지 관련 변수들을 불러들이는 함수를 만들어둔다.
페이지를 나눌때 고려할 부분은 "한 페이지에 몇개의 리스트를 불러오느냐" 인데, 이 부분을 SQL 쿼리문으로 조절을 해주어야 한다.
BoardAction.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <p> public class BoardAction implements Action { @Override public void execute(HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub BoardDAO dao = new BoardDAO(); ArrayList <span style= "font-family: "맑은 고딕", sans-serif;" >list;</span></p><boarddto> int totalCount = dao.getTotalCount(); int page = request.getParameter( "page" ) == null ? 1 : Integer.parseInt(request.getParameter( "page" )); Paging paging = new Paging(); paging.setPageNo(page); //get방식의 parameter값으로 반은 page변수, 현재 페이지 번호 paging.setPageSize( 10 ); // 한페이지에 불러낼 게시물의 개수 지정 paging.setTotalCount(totalCount); page = (page - 1 ) * 10 ; //select해오는 기준을 구한다. list = dao.getList(page, paging.getPageSize()); request.setAttribute( "list" , list); request.setAttribute( "paging" , paging); } } </boarddto> |
Action 부분에서 DAO에 값을 지정해주고 View페이지에 값을 전달해주는 역할을 한다. Controller 역할
Action.java
1 2 3 | public interface Action { public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException; } |
BoardDAO.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | public class BoardDAO { DBCP dbcp = new DBCP(); Connection conn = null ; PreparedStatement pstmt = null ; Statement stmt = null ; ResultSet rs = null ; String sql = null ; public void closeDB() { try { if (rs != null ) rs.close(); if (stmt != null ) stmt.close(); if (pstmt != null ) pstmt.close(); if (conn != null ) conn.close(); } catch (SQLException e) { e.printStackTrace(); } } public ArrayList<boarddto> getList( int startRow, int endRow) { ArrayList<boarddto> list = new ArrayList<boarddto>(); try { conn = dbcp.getConnection(); sql = "select *, (select u_name from user where idx = writer_fk) writer, (select idx from answer where idx = answer_fk) answer from board order by idx desc limit " +startRow+ ", " +endRow; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { int idx = rs.getInt( "idx" ); String title = rs.getString( "title" ); int count = rs.getInt( "count" ); String writer = rs.getString( "writer" ); String answer = rs.getString( "answer" ); String enroll = rs.getString( "enroll" ); BoardDTO dto = new BoardDTO(); dto .setIdx(idx); dto .setTitle(title); dto .setCount(count); dto .setWriter(writer); dto .setAnswer(answer); dto .setEnroll(enroll); list.add(dto); } } catch (Exception e){ e.printStackTrace(); } finally { closeDB(); } return list; } public int getTotalCount(){ int total = 0 ; try { conn = dbcp.getConnection(); sql = "select count(*) from board" ; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); if (rs.next()){ total = rs.getInt( 1 ); } } catch (Exception e){ e.printStackTrace(); } finally { closeDB(); } return total; } } </boarddto></boarddto></boarddto> |
BoardController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | /** * Servlet implementation class BoardController */ @WebServlet ( "*.do" ) public class BoardController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public BoardController() { super (); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding( "UTF-8" ); String requestURI = request.getRequestURI(); String[] URIList = requestURI.split( "/" ); String cmdURI = URIList[URIList.length- 1 ]; Action action = null ; if (cmdURI.equals( "board.do" )) { action = new BoardAction(); action.execute(request, response); RequestDispatcher dis = request.getRequestDispatcher( "board.jsp" ); dis.forward(request, response); } } } |
이제 View Page에서 어떻게 출력하느냐이다.
JSTL 문법을 이용해서 구현하였다.
board.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> < div class = "toolbar-bottom" > < div class = "toolbar mt-lg" > < div class = "sorter" > < ul class = "pagination" > < li >< a href = "javascript:PageMove(${paging.firstPageNo})" >맨앞으로</ a ></ li > < li >< a href = "javascript:PageMove(${paging.prevPageNo})" >앞으로</ a ></ li > < c:foreach var = "i" begin = "${paging.startPageNo}" end = "${paging.endPageNo}" step = "1" > < c:choose > < c:when test = "${i eq paging.pageNo}" > < li class = "active" >< a href = "javascript:PageMove(${i})" >${i}</ a ></ li > </ c:when > < c:otherwise > < li >< a href = "javascript:PageMove(${i})" >${i}</ a ></ li > </ c:otherwise > </ c:choose > </ c:foreach > < li >< a href = "javascript:PageMove(${paging.nextPageNo})" >뒤로</ a ></ li > < li >< a href = "javascript:PageMove(${paging.finalPageNo})" >맨뒤로</ a ></ li > </ ul > </ div > </ div > </ div > |
1 2 3 | function PageMove(page){ location.href = "board.do?page=" +page; } |
'JSP' 카테고리의 다른 글
Session 관리하기 (0) | 2016.12.01 |
---|---|
Http통신을 이용한 JSON 받아오기 (0) | 2016.11.25 |
금액) 숫자 세자리마다 , 넣어주기 (0) | 2016.10.25 |
다음 우편번호 주소 API 사용하기 (1) | 2016.10.21 |
댓글