Jam's story

[JDBC] 페이징 처리 본문

JDBC

[JDBC] 페이징 처리

애플쩀 2022. 5. 10. 14:06

 

tbl_cstvsboard 테이블에 345 개의 게시글을 추가하는 익명 프로시저를 만들어서 추가하세요
declare
    vi number :=1;
    vwriter varchar2(20);
    vfirstname varchar2(6);
    vlastname varchar2(3);
    vpwd varchar2(20) := '1234';
    vemail varchar2(100) ;
    vtitle varchar2(200);
    vtag number(1);
    vcontent clob;
begin
while vi <= 345
    loop
    vlastname:= substr('김이박최차',trunc(dbms_random.value(1,6)),1);
    vfirstname:= substr('문자중지정된위취를숫자로리턴한다', trunc(dbms_random.value(1,17)),2);
    vwriter := vlastname||vfirstname;
     vemail  := dbms_random.string('a',5)||'@sist.co.kr';
     vtitle := dbms_random.string('u',10);
     vtag := trunc(dbms_random.value(0,2));
     vcontent := dbms_random.string('a',10);
        insert into tbl_cstvsboard(seq,writer,pwd,email,title,tag,content)
        values (seq_tbl_cstvsboard.nextval,vwriter,vpwd,vemail,vtitle,vtag,vcontent);
        vi := vi+1;
    end loop;
--exception
end;



----------------------------------------------------------
desc tbl_cstvsboard;
select trunc(dbms_random.value(1,6)),  trunc(dbms_random.value(1,17))from dual;

--Lastname
select substr('김이박최차',trunc(dbms_random.value(1,6)),1)lastname,
substr('문자중지정된위취를숫자로리턴한다', trunc(dbms_random.value(1,17)),2)firtname
,dbms_random.string('a',5)||'@sist.co.kr'
from dual;

총페이지수 구하기

자바

public static void main(String[] args) {
		//한페이지에 출력할 게시글 수 
		int numberPerPage=15;
		//현재페이지
		int currentPage=1;
		//--게시글수: 346
		//--총페이지수: 23.06666666666666666666666666666666666667 ->24
		int totalRecords=346;  //나중엔 쿼리로 가져와야한다. 
		int totalPages=(int)Math.ceil((double)totalRecords/numberPerPage);

		
	}

오라클

select ceil(count(*)/15)
from tbl_cstvsboard;

 

현재 페이지 버튼 출력 

	for (int i = 1; i <= totalPages; i++) {
			startOfPageBlock=(i-1)/numberOfPageBlock*numberOfPageBlock+1;
			System.out.printf("현재 페이지:%d %d\n",i, startOfPageBlock);
		}

 

 

총정리 

 

package days05;

public class Ex01 {

	public static void main(String[] args) {
		//한페이지에 출력할 게시글 수 
		int numberPerPage=15;
		//현재페이지
		int currentPage=1;
		//--게시글수: 346
		//--총페이지수: 23.06666666666666666666666666666666666667 ->24
		int totalRecords=346;  //나중엔 쿼리로 가져와야한다. 
		//Math.ceil은 double형이기 때문에 형변환 
		int totalPages=(int)Math.ceil((double)totalRecords/numberPerPage);
		int numberOfPageBlock=10;
		//페이징 블럭의 시작값
		int startOfPageBlock=1;
		int endOfPageBlock;
	
		for (int i = 1; i <= totalPages; i++) {
			startOfPageBlock=(i-1)/numberOfPageBlock*numberOfPageBlock+1;
			endOfPageBlock= startOfPageBlock+numberOfPageBlock-1;
			if(endOfPageBlock>totalPages) endOfPageBlock=totalPages;
			System.out.printf("현재 페이지:%d \t",i);
			
			//이전버튼보이게, start1이면 안보임 
			if(startOfPageBlock!=1) System.out.print("<");
			
			for (int j = 	startOfPageBlock; j < endOfPageBlock; j++) {
				System.out.printf(j==i?" [%d] ":" %d ",j);
			}
			//다음버튼보이게, 마지막페이지에서는 안 보임 
			if(endOfPageBlock!=totalPages) System.out.print(">");
			System.out.println();
		}
	}

}

결과물

 

 

총레코드수 테스트 

 

 

 

 

 

어제 만든 Board 수정 

 

DAO.java

	//총레코드 수 반환하는 메소드 
	int getTotalRecords() throws SQLException;
	
	//총페이지수 반환하는 메소드 
	//한페이지에 출력할 수 있는 매개변수를 받는다. ->활용도 높이기 위해 
	int getTotalPages(int numberPerPages) throws SQLException;

 

DAOimpl.java

	@Override
	public int getTotalRecords() throws SQLException {
		String sql="select count(*) from tbl_cstvsboard";
		int totalRecords=0;
		
		this.pstmt=this.conn.prepareStatement(sql);
		this.rs=this.pstmt.executeQuery();
		
		this.rs.next();
		totalRecords=rs.getInt(1);
		
		this.rs.close();
		this.pstmt.close();
		
		return totalRecords;
	}
    
    //총 페이지수 반환 
	public int getTotalPages(int numberPerPages) throws SQLException {
		String sql="select ceil(count(*)/?) from tbl_cstvsboard";
		
		this.pstmt=this.conn.prepareStatement(sql);
		this.pstmt.setInt(1, numberPerPages);
		this.rs=this.pstmt.executeQuery();
		
		this.rs.next();
		int TotalPages=rs.getInt(1);
		
		
		this.rs.close();
		this.pstmt.close();
		
		return TotalPages;
	}

 

Test.java

실행할때는 run as에서 junit test 로 

/*
	 * public void getTotalRecords_test() { Connection conn=DBconn.getConnection();
	 * 
	 * BoardDAOImpl dao = new BoardDAOImpl( ); dao.setConn(conn); try { int
	 * totalRecords=dao.getTotalRecords(); System.out.println(totalRecords); } catch
	 * (SQLException e) { // TODO: handle exception }finally {DBconn.close();}
	 * 
	 * }
	 */
	public void gettotalPages() {
	Connection conn=DBconn.getConnection();
		BoardDAOImpl  dao = new BoardDAOImpl(  );
		dao.setConn(conn);
		
		try {
			int totalPages=dao.getTotalPages(15);
			System.out.println("총페이지수: "+totalPages);
		} catch (SQLException e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {DBconn.close();}
		
	}

 

현재페이지에 해당되는 게시글 목록 반환 하는 메소드 선언 

DAO 인터페이스 

	//9.  현재페이지에 해당되는 게시글 목록 반환 하는 메소드 선언 중복선언 오버로딩 
	//한페이지에 몇개, 몇번페이지를 볼껀지 
	public abstract ArrayList<BoardDTO> select(int currentPage,int numberPerPage) throws SQLException;
	// 2. 새로운 게시글 추가하는 메서드 선언

 

 

BoardDAOImpl.java

String sql 바꾸기 (오라클)  [내일 시험문제 2번]

SELECT seq,  writer, email, title, readed , writedate 
FROM tbl_cstvsboard 
ORDER BY seq DESC

--2
select rownum no, t.*
from(
SELECT seq,  writer, email, title, readed , writedate 
FROM tbl_cstvsboard 
ORDER BY seq DESC
)t


--3
SELECT *
FROM ( 
    SELECT ROWNUM no, t.*
    FROM (
        SELECT seq,  writer, email, title, readed , writedate  
        FROM tbl_cstvsboard  
        ORDER BY seq DESC
    ) t
) m
WHERE m.no BETWEEN   ( (:currentPage -1)*:numberPerPage +1  )  AND (:currentPage -1)*:numberPerPage +1 + :numberPerPage -1 ;

 

BoardDAOImpl.java

@Override
	public ArrayList<BoardDTO> select() throws SQLException {
		
		ArrayList<BoardDTO>  list = null;
		BoardDTO dto = null;
		
		int seq;
		String writer; 
		String email;
		String title;
		Date   writedate;
		int readed; 
		
		String sql =   "SELECT seq,  writer, email, title, readed , writedate "
							+ "FROM tbl_cstvsboard "
							+ "ORDER BY seq DESC";
		
		//System.out.println(  sql );
		
		this.pstmt = this.conn.prepareStatement(sql);
		this.rs  = this.pstmt.executeQuery();
		
		if( this.rs.next() ) {
			list = new ArrayList<BoardDTO>();
			do {
				
				seq = this.rs.getInt("seq");
				writer = this.rs.getString("writer");
				email = this.rs.getString("email");
				title = this.rs.getString("title");
				writedate = this.rs.getDate("writedate");
				readed = this.rs.getInt("readed");
				
				dto = new BoardDTO(seq, writer, email, title, writedate, readed);
				
				list.add(dto);
			} while ( this.rs.next() );
		} // if
		
		this.rs.close();
		this.pstmt.close();
		
		return list;
	}

 

test

	@Test
	public void select_test() {
		Connection conn = DBconn.getConnection();
		
		// 1. 생성자 DI
		//BoardDAOImpl  dao = new BoardDAOImpl( conn );
		
		// 2. Setter DI
		BoardDAOImpl  dao = new BoardDAOImpl(  );
		dao.setConn(conn);
		
		ArrayList<BoardDTO> list = null;
		try {
			//list = dao.select();
			list=dao.select(1,15);
			if ( list == null) {
				System.out.println("> 게시글이 존재 X");
			} else {
				Iterator<BoardDTO> ir = list.iterator();
				while (ir.hasNext()) {
					BoardDTO dto =  ir.next();
					System.out.println(  dto );
				}
			} // if
		} catch (SQLException e) { 
			e.printStackTrace();
		} finally {
			DBconn.close();
		}

 

Boardservice

	//1,1 게시글 목록 서비스 메소드+페이징 처리 추가 
	public ArrayList<BoardDTO> selectService(int currentPage, int numberPerPage){
		ArrayList<BoardDTO> list = null;
		
		try {
			// 1. 로그 기록 서비스
			System.out.println("> 게시글 목록 조회 -> 로그 기록 작업...");
			// 2. 게시글 목록
			list = this.dao.select(currentPage,  numberPerPage);
		} catch (SQLException e) { 
			e.printStackTrace();
		}
		return list;
	}

 

Controller  목록보기 

ArrayList<BoardDTO> list = this.service.selectService(this.currentPage, this.numberOfPageBlock);

String pagingBlock=this.service.pageService(this.currentPage,

 this.numberPerPage, this.numberOfPageBlock); //위와 같은 것을 문자열로 돌려주는 함수 
System.out.println(pagingBlock);
System.out.println(pagingBlock); 

이부분만 수정하고 나머지는 예전과 같다. 

	// 게시글 목록 조회 메서드
	private void 목록보기() {
		
		System.out.println("현재페이지 currentPage 입력:");
		this.currentPage=this.scanner.nextInt();
		ArrayList<BoardDTO> list = this.service.selectService(this.currentPage, this.numberOfPageBlock);

		// 뷰(View) - 출력 담당
		System.out.println("\t\t\t  게시판");
		System.out.println("--------------------------------------------------------------");
		System.out.printf("%s\t%-40s\t%s\t%-10s\t%s\n", 
				"글번호","글제목","글쓴이","작성일","조회수");
		System.out.println("--------------------------------------------------------------");

		if ( list == null) {
			System.out.println("\t\t > 게시글 존재 X ");
		} else {
			Iterator<BoardDTO> ir =  list.iterator();
			while (ir.hasNext()) {
				BoardDTO dto =   ir.next();
				System.out.printf("%d\t%-30s  %s\t%-10s\t%d\n",
						dto.getSeq(), 
						dto.getTitle(),
						dto.getWriter(),
						dto.getWritedate(),
						dto.getReaded());				
			}
		}

		System.out.println("--------------------------------------------------------------");
		//System.out.println("\t\t\t [1] 2 3 4 5 6 7 8 9 10 >");  // 페이징블럭
		String pagingBlock=this.service.pageService(this.currentPage, this.numberPerPage, this.numberOfPageBlock); //위와 같은 것을 문자열로 돌려주는 함수 
		System.out.println(pagingBlock);
		System.out.println("--------------------------------------------------------------");

		일시정지();
	}

 

String pagingBlock=this.service.pageService(this.currentPage,

 this.numberPerPage, this.numberOfPageBlock); //위와 같은 것을 문자열로 돌려주는 함수 
System.out.println(pagingBlock);
System.out.println(pagingBlock); 를 추가해서 

 

service에 메소드 추가 

public String pageService(int currentPage, int numberPerPage, int numberOfPageBlock) {
      String pagingBlock =  "\t\t\t";
   
      try {
         // int totalRecords =  this.dao.getTotalRecords();
         int totalPages    =  this.dao.getTotalPages(numberPerPage);         
         int startOfPageBlock = 1;
         int endOfPageBlock ;
         // ****
         startOfPageBlock = (currentPage -1) /numberOfPageBlock * numberOfPageBlock +1 ;
         endOfPageBlock = startOfPageBlock + numberOfPageBlock -1;
         if(  endOfPageBlock > totalPages ) endOfPageBlock = totalPages;
         
         if( startOfPageBlock != 1 ) pagingBlock +=" < ";         
         for (int j = startOfPageBlock; j <= endOfPageBlock ; j++) {
             pagingBlock +=    String.format(j==currentPage?"[%d] ":"%d ", j);
         }         
         if( endOfPageBlock != totalPages )  pagingBlock +=" <> ";         
      } catch (SQLException e) { 
         e.printStackTrace();
      } 
      
      return pagingBlock;
   }

결과물

 

Comments