JSP

* 페이지 나누기
- 페이지당 게시물수 : 10개
- 전체 게시물수 : 999개
- 몇 페이지? : 100
    999 / 10 => 99.9 올림 => 100
    
- 페이지의 시작번호, 끝번호 계산
where rn between 1 and 10
    1페이지 => 1 ~ 10
    2페이지 => 11 ~ 20
    ....
    11페이지 => 101 ~ 110
    57페이지 => 561 ~ 561
    99페이지 => 981 ~ 990
    100페이지 => 991 ~ 1000
    시작번호=(현재페이지 - 1 ) * 페이지당게시물수 + 1
        1페이지 => (1-1) * 10 + 1 => 1
        2페이지 => (2-1) * 10 + 1 => 11
        7페이지 => (7-1) * 10 + 1 => 61
    끝번호=시작번호 + 페이지당게시물수 - 1
        1페이지 => 1 + 10 - 1 => 10
        2페이지 => 11 + 10 - 1 => 20

* 전체 페이지 블록수
    전체페이지갯수 / 10
    57 / 10 => 5.7 => 6개

1 2 3 4 5 6 7 8 9 10 [다음]
[이전] 11 12 13 14 15 16 17 18 19 20 [다음]

[이전] 41 42 43 44 45 46 47 48 49 50 [다음]
[이전] 51 52 53 54 55 56 57     58 59 60 [다음]
[이전] 61 62 

  현재 페이지가 속한 블록
  
현재블록=(현재페이지-1)/페이지블록단위 + 1

    1페이지 => 몇번째 블록? 1
        (1-1)/10 + 1 =>1
    9페이지 =>         1블록
        (9-1)/10 + 1 => 1
    11페이지 => 2블록
        (11-1)/10 + 1 =>2
    57페이지 
        (57-1)/10 + 1 =>6 
        
* 페이지 블록의 시작번호
(현재블록-1)*블록단위+1
    1블록 => (1-1)*10 + 1 => 1
    2블록 => (2-1)*10 + 1 => 11
    6블록 => (6-1)*10 + 1 => 51
    
* 페이지 블록의 끝번호
블록시작번호+블록단위-1;
    1블록 => 1+10-1 => 10
    2블록 => 11+10-1 => 20
    6블록 => 51+10-1 => 60     
            

 

 

 

 


SQL


drop table test;

create table test
    as select * from emp where 1=0;
    
-- 1000건 입력

declare  -- 선언문
    i number :=1;
begin
    while i<= 1000 loop
    insert into test(empno, ename) values(i, '사원'||i);
    i :=i+1;
end loop;

end;
/

commit;

select count(*)    from test;    

-- rownum 레코드의 순번
-- from => where => select => order by
select * from 
(
    select  rownum as rn ,A.* -- A 테이블에 일려번호를 매김 
    from ( --전체 레코드
        select  empno, ename 
        from test order by empno 
    ) A 
) where rn between 11 and 20 -- 부여된 일련번호로 조회


 

 

MybatisManager

package sqlmap;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



public class MybatisManager {
//싱글톤 패턴으로 SqlSessionFactory 생성
//SqlSessionFactoryBuilder => SqlSessionFactory
//=>SqlSession
//(sql 실행 객체 : JDBC의 Statement + Result 객체 )
	
	private static SqlSessionFactory instance;
	private MybatisManager() {} //private 생성자
	
	public static SqlSessionFactory getInstance(){
		Reader reader=null;
		try {
			// Java Resources의 src
			//mybatis 설정파일 정보를 읽음
			reader = Resources.getResourceAsReader(
					"sqlmap/sqlMapConfig.xml");
			//SqlSessionFactory 생성기
			instance = new SqlSessionFactoryBuilder().build(reader);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try{
				if(reader!=null)reader.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return instance;
	}
	
	
	
}

 

sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- xml 지시어, xml directive -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 알리아스 설정 -->
	<typeAliases>
<!-- typeAlias type="전체경로" alias="별칭" -->	
	 <!--  <typeAlias type="emp.dto.EmpDTO" alias="e" /> -->
	</typeAliases>
	
	<!-- db연결 참조코드 -->
<!-- 	<environments default="">
		<environment id="">
			<transactionManager type="JDBC" />
			<dataSource type="JNDI">
				<property name="data_source" 
				value="java:comp/env/jdbc/myoracle" />
			</dataSource>
		</environment>
	</environments> -->
	
<!-- 	
	    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/testDB" />
                <property name="username" value="test" />
                <property name="password" value="test12" />
            </dataSource>
        </environment>
    </environments>

 -->

	
	<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="oracle.jdbc.OracleDriver" />
                <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:xe" />
                <property name="username" value="java" />
                <property name="password" value="1111" />
            </dataSource>
        </environment>
    </environments>


	<mappers>
		<mapper resource="/memo/mapper/memo.xml"/>
		<mapper resource="guestbook/mapper/guestbook.xml"/>
		<mapper resource="page/emp.xml"/>
	</mappers>
	
	
	
	<!-- 실제 sql query -->
<!-- 	<mappers>
		<mapper resource="emp/mapper/emp.xml" />
		<mapper resource=
			"student/mapper/student.xml" />		
		<mapper resource=
			"student/mapper/dept.xml" />	
		<mapper resource=
			"student/mapper/prof.xml" />	
		<mapper resource=
			"student/mapper/lecture.xml" />		
		<mapper resource=
			"memo/mapper/memo.xml" />	
		<mapper resource=
			"board/mapper/board.xml" />												
	</mappers> -->
	
</configuration>

 

 

emp.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">
<!-- memo.xml -->
<!-- 저장 프로시저 호출 방법 { call 프로시저이름(매개변수) } -->
<mapper namespace="emp">

<!-- 네임스페이스 id는 중복이 될 수 없음 -->
	<select id="empList" resultType="page.EmpDTO">
	
		select * from 
		(
		    select  rownum as rn ,A.*  
		    from ( --전체 레코드
		        select  empno, ename 
		        from test order by empno 
		    ) A 
		) where rn between #{start} and #{end}

	</select>
	

	
</mapper>


 

 

EmpDTO

package page;

public class EmpDTO {
	private int empno;
	private String ename;
	
	public int getEmpno() {
		return empno;
	}
	public void setEmpno(int empno) {
		this.empno = empno;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	
	@Override
	public String toString() {
		return "EmpDTO [empno=" + empno + ", ename=" + ename + "]";
	}
	
	
}

 

EmpDAO

package page;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import sqlmap.MybatisManager;

public class EmpDAO {
	
	public List<EmpDTO> empList(int start, int end){
		List<EmpDTO> items=new ArrayList<>();
		SqlSession session=null;
		try{
			session=MybatisManager.getInstance().openSession();
			//페이지 나누기 에 필요한 start , end 값 전달
			Map<String, Object> map=new HashMap<>();
			map.put("start", start);
			map.put("end", end);
			items=session.selectList("emp.empList", map);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(session!=null)session.close();
		}
		return items;
	}
	
	
}

 

PageController

package page;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/page_servlet/*")
public class PageController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String url =request.getRequestURL().toString();
		EmpDAO dao=new EmpDAO();
		
		if(url.indexOf("list.do")!=-1){
		//	System.out.println("서블릿 호출");
					
//			for(EmpDTO row : list){
//				System.out.println(row.toString());
//			}
			
			int count=1000;//레코드 갯수
			int curPage=1;//현재 페이지 번호
			if(request.getParameter("curPage")!=null){
				curPage=Integer.parseInt(request.getParameter("curPage"));
			}
			Pager pager=new Pager(count, curPage, 10, 10);
			int start=pager.getPageBegin();//레코드 시작 번호
			int end=pager.getPageEnd();//레코드 끝 번호
			List<EmpDTO> list=dao.empList(start, end);
			
			request.setAttribute("list", list);
			request.setAttribute("page", pager);
			String page="/page/list.jsp";
			RequestDispatcher rd=
					request.getRequestDispatcher(page);
			rd.forward(request, response);
		}
	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

 

Pager

package page;

public class Pager {
	//페이지당 게시물수
//	public static final int PAGE_SCALE=10;
	// 페이지 블록 단위(한 화면에 보여줄 페이지 수)
//	public static final int BLOCK_SCALE=10;

	public int PAGE_SCALE=10;
	// 페이지 블록 단위(한 화면에 보여줄 페이지 수)
	public int BLOCK_SCALE=10;
	
	
	private int curPage; //현재 페이지
	private int prevPage; //이전 페이지
	private int nextPage; //다음 페이지
	private int totPage; // 전체 페이지 갯수
	private int totBlock; //전체 블록 갯수
	private int curBlock; //현재 페이지 블록
	private int prevBlock; //이전 페이지 블록
	private int nextBlock; //다음 페이지 블록
	private int pageBegin; //현재 페이지 시작 번호
	private int pageEnd; //현재 페이지 끝 번호
	private int blockStart; //현재 블록의 시작 번호
	private int blockEnd; // 현재 블록의 끝 번호
	
	
	//생성자( 전체레코드 갯수, 페이지 번호)
	public Pager(int count, int curPage, Integer PAGE_SCALE, Integer BLOCK_SCALE){
		curBlock=1; //현재 페이지 블록
		this.curPage=curPage;

		if(PAGE_SCALE==null) this.PAGE_SCALE=10;
		else  this.PAGE_SCALE=PAGE_SCALE;
		
		if(BLOCK_SCALE==null)this.BLOCK_SCALE=10;
		else this.BLOCK_SCALE=BLOCK_SCALE;
		
		setTotPage(count);// 전체 페이지 갯수 설정
		setPageRange();
		setTotBlock(); //전체 페이지 블록 갯수 설정
		//curPage 가 속한 페이지 블록의 시작번호, 끝번호계산
		setBlockRange(); //페이지 블록의 시작, 끝 번호 계산
	}	
	
	public void setBlockRange(){
//		현재블록=(현재페이지-1)/페이지블록단위 + 1
//
//				1페이지 => 몇번째 블록? 1
//					(1-1)/10 + 1 =>1
//				9페이지 => 		1블록
//					(9-1)/10 + 1 => 1
//				11페이지 => 2블록
//					(11-1)/10 + 1 =>2
//				57페이지 
//					(57-1)/10 + 1 =>6 
		
		curBlock =(int)Math.ceil((curPage-1)/BLOCK_SCALE)+1;

		
//		* 페이지 블록의 시작번호
//		(현재블록-1)*블록단위+1
//			1블록 => (1-1)*10 + 1 => 1
//			2블록 => (2-1)*10 + 1 => 11
//			6블록 => (6-1)*10 + 1 => 51		
		blockStart=(curBlock-1)*BLOCK_SCALE+1;

//		* 페이지 블록의 끝번호
//		블록시작번호+블록단위-1;
//			1블록 => 1+10-1 => 10
//			2블록 => 11+10-1 => 20
//			6블록 => 51+10-1 => 60 			
		blockEnd=blockStart+BLOCK_SCALE-1;
		
		if(blockEnd>totPage){
			blockEnd=totPage;
		}
		prevPage=curBlock==1? 1:(curBlock-1)*BLOCK_SCALE;
		nextPage=curBlock>totBlock?
				(curBlock*BLOCK_SCALE):(curBlock*BLOCK_SCALE)+1;

		if(nextPage>=totPage){
			nextPage=totPage;
		}
		
	}
	
	
	public void setTotBlock(){
//		* 전체 페이지 블록수
//		전체페이지갯수 / 10
//		57 / 10 => 5.7 => 6개				
		//전체페이지갯수 / 페이지블록단위
		totBlock = (int)Math.ceil(totPage / BLOCK_SCALE);
	}
	
	//현재 페이지의 start, end 계산
	public void setPageRange(){
//		1페이지 => 1 ~ 10
//				2페이지 => 11 ~ 20
//				....
//				11페이지 => 101 ~ 110
//				57페이지 => 561 ~ 561
//				99페이지 => 981 ~ 990
//				100페이지 => 991 ~ 1000
//				시작번호=(현재페이지 - 1 ) * 페이지당게시물수 + 1
//					1페이지 => (1-1) * 10 + 1 => 1
//					2페이지 => (2-1) * 10 + 1 => 11
//					7페이지 => (7-1) * 10 + 1 => 61
//		
		pageBegin=(curPage-1)*PAGE_SCALE+1;
		pageEnd=pageBegin+PAGE_SCALE -1;
	}
	
	
	public int getPAGE_SCALE() {
		return PAGE_SCALE;
	}
	public void setPAGE_SCALE(int pAGE_SCALE) {
		PAGE_SCALE = pAGE_SCALE;
	}
	public int getBLOCK_SCALE() {
		return BLOCK_SCALE;
	}
	public void setBLOCK_SCALE(int bLOCK_SCALE) {
		BLOCK_SCALE = bLOCK_SCALE;
	}
	public int getCurPage() {
		return curPage;
	}
	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}
	public int getPrevPage() {
		return prevPage;
	}
	public void setPrevPage(int prevPage) {
		this.prevPage = prevPage;
	}
	public int getNextPage() {
		return nextPage;
	}
	public void setNextPage(int nextPage) {
		this.nextPage = nextPage;
	}
	public int getTotPage() {
		return totPage;
	}
	
	//레코드갯수로 전체 페이지 갯수 계산
	public void setTotPage(int count) {
		//Math.ceil() 올림함수
		//991개  991/10 => 99.1
		totPage = (int)Math.ceil(count*1.0/PAGE_SCALE);
	}
	
	public int getTotBlock() {
		return totBlock;
	}
	public void setTotBlock(int totBlock) {
		this.totBlock = totBlock;
	}
	public int getCurBlock() {
		return curBlock;
	}
	public void setCurBlock(int curBlock) {
		this.curBlock = curBlock;
	}
	public int getPrevBlock() {
		return prevBlock;
	}
	public void setPrevBlock(int prevBlock) {
		this.prevBlock = prevBlock;
	}
	public int getNextBlock() {
		return nextBlock;
	}
	public void setNextBlock(int nextBlock) {
		this.nextBlock = nextBlock;
	}
	public int getPageBegin() {
		return pageBegin;
	}
	public void setPageBegin(int pageBegin) {
		this.pageBegin = pageBegin;
	}
	public int getPageEnd() {
		return pageEnd;
	}
	public void setPageEnd(int pageEnd) {
		this.pageEnd = pageEnd;
	}
	public int getBlockStart() {
		return blockStart;
	}
	public void setBlockStart(int blockStart) {
		this.blockStart = blockStart;
	}
	public int getBlockEnd() {
		return blockEnd;
	}
	public void setBlockEnd(int blockEnd) {
		this.blockEnd = blockEnd;
	}

	
	
	
	
}

 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>    
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
a:link {text-decoration:none;}
a:visited {text-decoration: none;}
a:hover{color:red; text-decoration:none;}
a:activie{color:yellow; text-decoration:none;}
</style>

<script>
$(function(){
	list("1");
});

function list(curPage){
	var param="curPage="+curPage;

	$.ajax({
		type:"post",
		url:"${path}/page_servlet/list.do",
		data:param,
		success:function(result){
			$("#result").html(result);		
		}
	});
}

</script>

</head>
<body>

<h2>페이지 나누기</h2>
<div id="result"></div>




</body>
</html>

 

 

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="../include/header.jsp" %>    

<table border="1" style="width:500px;">
 <tr>
 	<th>사번</th>
 	<th>이름</th>
 </tr>
 
<c:forEach var="row" items="${list}">
 <tr>
   <td>${row.empno}</td>
   <td>${row.ename}</td>
 </tr>
</c:forEach>
 
 

<!-- 페이지 네비게이션 출력 영역 --> 

 <tr align="center">
   <td colspan="2">
    <!-- [처음] -->
    <c:if test="${page.curPage >1 }">
    	<a href="#" onclick="list(1)">[처음]</a>
    </c:if>
   
    <!-- [이전] -->
    <c:if test="${page.curBlock >1 }">
    	<a href="#" onclick="list(${page.prevPage})">[이전]</a>
    </c:if>
   
   <c:forEach var="num" begin="${page.blockStart}"
	end="${page.blockEnd}">
	  <c:choose>
	  	<c:when test="${num == page.curPage}">
	  	  <span style="color:red">${num}</span>
	  	</c:when>
	  	<c:otherwise>
	  	  <a href=
"javascript:list('${num}','${search_option}','${keyword}')">${num}</a>	
	  	</c:otherwise>
	  </c:choose>	  
   </c:forEach> 

	  <!-- [다음] -->
    <c:if test="${page.curBlock < page.totBlock }">
    	<a href="#" onclick="list(${page.nextPage})">[다음]</a>
    </c:if>
   
    <!-- [마지막] -->
    <c:if test="${page.curPage <page.totPage }">
    	<a href="#" onclick="list(${page.totPage})">[마지막]</a>
    </c:if>


   
   </td>
   
 </tr> 



 
 
</table>

 

 

 

페이지 나누기

사번 이름
101 사원101
102 사원102
103 사원103
104 사원104
105 사원105
106 사원106
107 사원107
108 사원108
109 사원109
110 사원110
[처음] [이전] 11 12 13 14 15 16 17 18 19 20 [다음] [마지막]

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

진실성이 결여된 칭찬은 칭찬이 아니라 아첨일 뿐이다. - V.M. 위고

댓글 ( 4)

댓글 남기기

작성