본문 바로가기

개발중/참고 기능

게시물 페이징

728x90
반응형

 

index.jsp

 프로그램이 실행 되면

glist.do 호출

 

 

 

 

 

 

 

GuestListController

@WebServlet("/glist.do")

 필요한 변수들을은 glist.do 에 정의한다.

 여기서 페이지를 계산해서 쿼리문에 보내줄 것이다.

 

 

 

 

 

 

 pageNum을 get해.

 

 

 

 

 if 문을 실행하는 경우는 처음 시작했을 때는

[ 1 ] 페이지를 보여줘야 하기 때문에

 

 

 

 

게시물의 start , end 를 구하는 공식

 

 

 

 

 

 

 

 

 

 

 

Gtotal 도 구해올 것

 

 

 

 

 

 

 

 

페이징의 수를 구하는 공식

 

 

 

 

 

마지막 페이지가

조회할 수 있는 페이지보다 많을 경우에는

조회할 수 있는 페이지를 마지막 페이지로 만든다

 

 

 

 

자 이제

내가 구한 것들을

너에게 보내줄께.

 

 

 

 

 

GuestSQL.java

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

start와 end 를 삽입하여서

쿼리문을 만들고

 

조회한 결과를 가지고 list에 실어서 보낸다

 

 

 

 

 

 

 

 

 

 

 

 

 

GuestListController

@WebServlet("/glist.do")

LG에 저장하고

 

 

 

 

 

 

 

실어서

 

 

 

 

 

 

 

forward 시키자

 

 

 

 

 

 

 

 

guestList.jsp

간편히 받아서

간편히 출력

 

 

 

 

 

 

 

 물론 페이지도

이렇게나 간단하게..

 

 

 

 

 

 

[ 완성본 ]

guestList.jsp

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> [guestList.jsp]  </title>
  <style type="text/css">
   
	*{ font-size: 20pt; }
	a{ font-size: 18pt; color:blue; text-decoration:none; }
	a:hover{ font-size:20pt; color:green;  text-decoration:none;  }
	#span_rcnt { font-size:16pt; color:red; }
  </style>
	
  <script type="text/javascript">
    function clearText(){
	   document.sform.keyword.value="";
	   document.sform.keyword.focus();
	}
  </script>
</head>
<body>
  
 <table width="1200" border="1" cellspacing="0">
   <tr align="right">
   	 <td colspan="6">
   	   <a href="guestWrite.jsp">[신규등록]</a> 
   	   <a href="index.jsp">[index]</a> 
   	   <a href="login.jsp">[로그인]</a> &nbsp;
   	   <a href="glist.do">[전체출력]</a> &nbsp;
   	      총레코드갯수:${Gtotal} &nbsp;&nbsp;
   	  </td>
   </tr>
   
  <tr bgcolor="yellow">
    <td>행번호</td>  <td>사번</td> <td>이름</td> 
    <td>제목</td>   <td>날짜</td> <td>조회수</td>  
  </tr>

  <c:forEach var="dto" items="${LG}">  
   <tr>
     <td> ${dto.rn} </td> 
     <td> ${dto.sabun} </td> 
     <td> ${dto.name} </td> 
     <td> <a href="gdetail.do?idx=${dto.sabun}"> ${dto.title}  </a> </td> 
     <td> ${dto.wdate} </td> 
     <td> ${dto.hit} </td>
   </tr>
 </c:forEach>

 <tr>
   <td colspan="6" align="center"> 
   	 <c:forEach var="i" begin="${startpage}" end="${endpage}" step="1">
   	    <a href="glist.do?pageNum=${i}"> [${i}] </a>	
   	 </c:forEach>
   </td>
 </tr>
   
 <tr>
   <td colspan="6" align="center">  
     <form name="sform">
        <b>검색:</b>
       <select name="keyfield" onchange="clearText();">
         <option value="">---검색선택--- </option>
         <option value="name" >이름검색</option>
         <option value="title"  >제목검색</option>
         <option value="">내용검색</option>
       </select>
       <input type="text" name="keyword" size="10">
       <input type="submit" value=" 검 색 ">
     </form>
   </td>
 </tr> 
 
 </table>
</body>
</html>

glist.do

package net.tis.mvc;

import java.io.IOException;
import java.io.PrintWriter; //추가
import java.util.ArrayList;

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;

import net.tis.sql.GuestDTO; //추가
import net.tis.sql.GuestSQL; //추가


@WebServlet("/glist.do")
public class  GuestListController  extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 doUser(request,response);	 //필수
  }//end

  public  void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  doUser(request,response);	//필수
  }//end
  
  public  void doUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 response.setContentType("text/html; charset=UTF-8");
     PrintWriter out = response.getWriter();
     
     System.out.println("<h2>GuestListController.java</h2>");     
     //GuestListController.java문서 단독실행 가능
     
     String pnum; //<a href="guestList.jsp?pageNum=14"> [14] </a>
     int pageNUM, pagecount;  
     int start, end;
     int startpage, endpage ;
     int tmp; 
    
     String sqry=" ";
     String skey="", sval="" ;
     String returnpage="";
     
     pnum = request.getParameter("pageNum");
     
     if( pnum==null || pnum=="" ) { 
    	 pnum="1";
    	 }
     
     pageNUM = Integer.parseInt(pnum); //문자에서 숫자로 페이지번호기억 
     
     GuestDTO dto = new GuestDTO( );
     GuestSQL gs = new GuestSQL( );
     
     int Gtotal = gs.dbGtotal();
     
     start = (pageNUM-1)*10+1 ;  //[14]클릭하면 문자로 14로 기억  시작행 131
     end = pageNUM*10 ;    //[14]클릭하면 문자로 14로 기억  끝행 140
  //////////////////////////////////////////////////////////////////////////////////////////
  //guestList0731.jsp문서참고
  //총페이지 32페이지  pagecount
  //[11] [14클릭] [20]
  //시작페이지 11
  //끝페이지 20
     
  if (Gtotal%10==0) { 
	  pagecount = Gtotal/10; 
  } else { 
	  pagecount = (Gtotal/10)+1; 
  }
     
  tmp       = (pageNUM-1)%10;
  startpage = pageNUM-tmp;
  endpage   = startpage+9;
  
  if( endpage > pagecount ) { 
	  endpage=pagecount ; 
  }
		  
     //ArrayList<GuestDTO> LG = gs.dbSelect(); 처음원본
     ArrayList<GuestDTO> LG = gs.dbSelect(start,end);
     request.setAttribute("LG", LG);
     request.setAttribute("Gtotal", Gtotal);
     request.setAttribute("startpage", startpage);
     request.setAttribute("endpage", endpage);
     request.setAttribute("pagecount", pagecount);
     
    RequestDispatcher dis = request.getRequestDispatcher("guestList.jsp");
    dis.forward(request, response);
  }//end
}//class END

GuestSQL.java

package net.tis.sql;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import net.tis.common.DB;
import java.text.SimpleDateFormat;

public class GuestSQL {
	  Connection CN ;
	  Statement ST ;
	  PreparedStatement PST;
	  CallableStatement CST;
	  ResultSet RS ;
	 
	  int Gsabun,Gpay, Ghit ;
	  int GGtotal; //전체레코드갯수
	  int Gtotal ; //조회레코드갯수
	  int GStotal=0 ; //Gtotal대신 GStotal사용도 좋습니다조회갯수
	 
	  String Gname,Gtitle, Gemail ;
	  java.util.Date Gwdate;
	 
	  String msg;
	  String submsg;
	  String Gdata;
	 
	  //댓글관련전역변수
	  int Rrn, Rnum, Rsabun ;
	  String Rwriter, Rcontent ;
	  int Rcnt ; //댓글갯수표시
	
	 //////////////////////////////////////////////////////
   public GuestSQL() {
  	 CN = DB.getConnection(); //08-25-화요일 다시 주석풀고 코드화
	 /*
  	 try {
  		Context ct = new InitialContext();
  		DataSource ds = (DataSource)ct.lookup("java:comp/env/jdbc/snow");
  		CN=ds.getConnection();  
  		System.out.println("dbcp  connection pool 연결성공성공 10:38  10:41 ");
  	}catch (Exception e){System.out.println("dbcp connection pool 연결에러:"+ e); 	}
    */
   }//end--------------------------------------------------------------------
   
  
   public void dbDelete( String data ) {
     try {
       msg="delete  from guest where sabun =  " + data ;
       ST=CN.createStatement();
       ST.executeUpdate(msg);
       System.out.println(data + " 데이터 삭제처리 성공했습니다");
  	 }catch(Exception ex) { System.out.println("에러:" + ex);} 
   }//end--------------------------------------------------------------------
   
    
   public void dbInsert(GuestDTO dto) {
  	 try {
   		msg="insert into guest values(?,?,?,sysdate,?,0,?)";
   		PST = CN.prepareStatement(msg);
   			PST.setInt(1,  dto.getSabun());
   			PST.setString(2, dto.getName());
   			PST.setString(3, dto.getTitle());
   			PST.setInt(4, dto.getPay());
   			PST.setString(5, dto.getEmail());
   		PST.executeUpdate(); //진짜저장
   		System.out.println("GuestSQL자바문서 dbInsert(dto)함수  저장성공  08-25-화요일 1:47");
   	 }catch(Exception ex) { System.out.println("저장에러:" + ex);}
   }//end--------------------------------------------------------------------
      
 	public ArrayList<GuestDTO> dbSelect(int start, int end){
 		ArrayList<GuestDTO> list = new ArrayList<GuestDTO>();
		try {
			String a="select * from ( ";
			String b=" select rownum rn, sabun,name,title, wdate,pay,hit,email from guest ";
			String c=") where rn between " + start + " and  " + end;
			
			msg = a+b+c ;
			
			ST=CN.createStatement();
			RS=ST.executeQuery(msg);
			while(RS.next()==true) {
				GuestDTO dto = new GuestDTO();
				 dto.setRn(RS.getInt("rn"));
				 dto.setSabun(RS.getInt("sabun")); 
				 dto.setName(RS.getString("name"));
				 dto.setTitle(RS.getString("title"));
				 dto.setWdate(RS.getDate("wdate")) ;
				 dto.setPay(RS.getInt("pay"));
				 dto.setHit(RS.getInt("hit"));
				 dto.setEmail(RS.getString("email"));
				 list.add(dto);
			}
		}catch(Exception ex){System.out.println("조회에러:" + ex); }
		return list;
	}//end--------------------------------------------------------------------
   
 	
 	//////////////////////////////////////////////////////////////////////////
  public int dbGtotal() {
 	 try {
 		 msg="select count(*) as cnt from guest ";
 		 ST = CN.createStatement();
 		 RS = ST.executeQuery(msg);
 		 if(RS.next()==true) { Gtotal= RS.getInt("cnt"); }
 		 //System.out.println("총갯수=" + Gtotal);
 	 }catch(Exception ex) { System.out.println("에러:" + ex);}
 	 return Gtotal;
  }//end--------------------------------------------------------------------
  
  public void dbTest() {//07-31-금요일 4:41분 생성
 	 try {
 		 int code=2400;
 		 String name="스프링";
 		 double point = 3.14;
 		 boolean gender=true;
 		 char grade='F' ; 
 		 //서로다른타입의 5개 데이터를 guestTest.jsp문서로 넘겨서 출력
 	 }catch(Exception ex) { System.out.println("에러:" + ex);}
  }//end--------------------------------------------------------------------
  
  
  
  public  GuestDTO  dbDetail(String Gdata) { //guestDetail.jsp문서연결
  	GuestDTO dto = new GuestDTO();
	try {
	  msg="select * from guest where sabun =  " + Gdata ;
	  ST=CN.createStatement();
	  RS=ST.executeQuery(msg); //조회한 한건 결과를 RS기억
	  if(RS.next()==true) { 
		dto.setSabun(RS.getInt("sabun")); 
		dto.setName(RS.getString("name"));
		dto.setTitle(RS.getString("title"));
		dto.setWdate(RS.getDate("wdate")) ;
		dto.setPay(RS.getInt("pay"));
		dto.setHit(RS.getInt("hit"));
		dto.setEmail(RS.getString("email"));
	   }
	 }catch(Exception ex) { System.out.println("에러:" + ex);}
 	 return dto;
  }//end--------------------------------------------------------------------
  
  
  public void dbEdit(GuestDTO dto) {
  	 try {
   		msg="update guest set  name=?, title=?, wdate=sysdate, pay=?, email=?  where sabun = ? ";
   		PST = CN.prepareStatement(msg);
   			PST.setString(1, dto.getName());
   			PST.setString(2, dto.getTitle());
   			PST.setInt(3, dto.getPay());
   			PST.setString(4, dto.getEmail());
   			PST.setInt(5,  dto.getSabun());
   		PST.executeUpdate(); //진짜수정update
   		System.out.println("GuestSQL자바문서 dbEdit(dto)함수  수정성공  08-26-수요일 점심시간이후");
   	 }catch(Exception ex) { System.out.println("수정에러:" + ex);}
  }//end--------------------------------------------------------------------
	 
  
  
   public void test() {
  	 try {
  		 //String a = " select * from  ( ";
  		 //String b = " select rownum rn, a.*, (select count(*) from guestreply r where r.sabun=a.sabun ) as rcnt from ";
  		 //String y = " ( select * from guest " + sqry + " order by sabun) a ";
  		 //String c = " ) where rn  between " + start + " and  " + end;
  	 }catch(Exception ex) { System.out.println("에러:" + ex);}
   }//end--------------------------------------------------------------------
}//GuestSQL class END

728x90
반응형