아무튼 개발
article thumbnail
반응형

지난 글에 이어 게시판 만들기 2번째 글이다.

저번에는 기초적인 기반이었다면 이번에는 페이징 처리를 추가로 알아보겠다.

 

 

<list.jsp>

 

<%
	MyUtil myUtil = new MyUtil();
	
	String pageNum = request.getParameter("pageNum");
	int currentPage = 1;	
	if(pageNum != null)		
		currentPage = Integer.parseInt(pageNum);
	
	String searchKey = request.getParameter("searchKey");
	String searchValue = request.getParameter("searchValue");
	
	if(searchValue!=null){		
		if(request.getMethod().equalsIgnoreCase("GET")){ 
			searchValue = URLDecoder.decode(searchValue,"UTF-8"); 			
		}		
		}else{
			searchKey = "subject";
			searchValue = ""; //null		
	}		
    
	int dataCount = dao.getDataCount(searchKey,searchValue);		
	int numPerPage = 3;		
	int totalPage = myUtil.getPageCount(numPerPage, dataCount);
		
	int start = (currentPage - 1)*numPerPage + 1;
	int end = currentPage*numPerPage;
		
	List<BoardDTO> lists = dao.getLists(start, end,searchKey,searchValue);	%>

 

지난 글에 이어 list의 뒷부분이다.

 

myUtil은 밑에 설명할 예정이며 거기서 메서드를 호출할 것이기에 미리 객체 생성을 해준다.

 

pageNum은 get방식으로 넘어오는 페이지 번호이며

currenPage는 1로 초기화하였다.

Integer~ 안에는 큰 따옴표 쓰지 않는 것 주의하자! 변수명을 써야 하기 때문이다.

 

String searchKey부터 Connection 앞까지 검색을 위한 코딩이다.

지난 BoardDAO파일에서 봤듯이 serachValue에 값이 있으면, 즉 검색을 했다면 한글로 썼을 테니 디코딩으로 풀어준다.

else는 검색을 안했을 때이다.

 

dataCount는 ScoreDAO에 있는 메서드로 select문에 count(*)을 써주었었다.

numPerPage는 하나의 페이지에 출력될 데이터 개수이다.

totalPage는 전체 페이지 개수이며 myUtil 역시 밑에서 확인하겠다.

 

start와 end는 가져올 데이터의 시작과 끝 번호이다.

 

(설명을 위해 중간에 다시 끊었다 진행)

 

<%   String param = "";
	if(!searchValue.equals("")){		
		param = "?searchKey=" + searchKey;
		param+= "&searchValue=" + URLEncoder.encode(searchValue, "UTF-8");
	}
	
	String listUrl = "list.jsp" + param;		
	String pageIndexList = myUtil.pageIndexList(currentPage, totalPage, listUrl);	
	String articleUrl = cp + "/board/article.jsp";
	
	if(param.equals("")){
		articleUrl += "?pageNum=" + currentPage;
	}else{
		articleUrl += param + "&pageNum=" + currentPage;
	}
		
	DBConn.close();   %>

첫 줄부터 if문까지 검색을 위한 코딩이다.

if문은 searchValue가 공백이 아니라면이므로 검색을 한 경우이다.

param은 웹페이지 url주소에 들어간다.

주소를 넘겨줄 땐 한글이니 인코딩을 하고 받을 땐 디코딩을 하므로, 인코딩을 해준다.

 

listUrl은 페이징 처리를 해주기 위함이다. 위의 param이 여기로 들어가며

param이 null일 경우 그대로이다.

 

articleUrl은 글을 눌렀을 때 나오는 article주소이다.

if문을 통해 페이지 번호와 검색 내용까지 함께 데리고 간다.

 

 

MyUtil.java

내용이 길기 때문에 위와 마찬가지로 역시 2개로 나누어 설명하겠다.

	//전체 페이지
	public int getPageCount(int numPerPage, int dataCount) {
    	int pageCount = 0;		
		pageCount = dataCount/numPerPage;
		
		if(dataCount%numPerPage != 0) {			
		pageCount++;
		}
		return pageCount;
	}
	
	//페이지 처리 메소드 
	public String pageIndexList(int currentPage, int totalPage, String listUrl) {
		
		int numPerBlock = 5;//◀이전 6 7 8 9 10 다음▶
		int currentPageSetup;//◀값 
		int page;//6 7 8 9 10
		
		StringBuffer sb = new StringBuffer();
		
		if(currentPage == 0 || totalPage ==0) {			
			return "";
		}
		
        if(listUrl.indexOf("?") != -1) {
			listUrl = listUrl + "&";			
		}else {
			listUrl = listUrl + "?";
		}

 

먼저 전체 페이지 구하는 메서드이다.

numPerPage는 하나의 페이지에 들어가는 데이터 개수이고

dataCount는 전체 데이터 개수를 의미한다.

전체 데이터 갯수를 각 페이지의 데이터 개수로 나눌 때 0이 아니면 페이지 수를 증가시킨다.

 

그다음은 페이징을 처리하는 메서드이다.

numPerBlock은 입력한 대로 6~10과 같이 표현할 페이지 번호의 개수이다.

currentPageSetup은 이전버튼에 들어갈 값이다.

page는 6~10을 의미한다.

 

if문으로 0일 경우를 미리 사전 방지하였다.

 

그다음 listUrl은 웹페이지의 url이다.

if문의 -1은 없을 때 리턴하는 값이므로 url에 ?가 있으면 진행한다.

검색한다면 &을 아니라면 ?을 뒤에 붙여준다.

 

 

		//◀이전의 '이전'에 들어가는 값
		currentPageSetup = (currentPage/numPerBlock)*numPerBlock;
		
		if(currentPage % numPerBlock == 0) {			
			currentPageSetup = currentPageSetup - numPerBlock;
		}
		
		//◀이전
		if(totalPage > numPerBlock && currentPageSetup > 0) {			
			sb.append("<a href=\"" + listUrl + "pageNum =" + currentPageSetup + "\">◀이전</a>&nbsp;");
		}
		
		//바로 가기 페이지 (6 7 8 9 10)
		page = currentPageSetup + 1;
		
		while(page <= totalPage && page <= (currentPageSetup + numPerBlock)) {
			
			if(page == currentPage) {				
				sb.append("<font color=\"Fuchsia\">" + page + "</font>&nbsp;");
			}else {				
				sb.append("<a href=\"" + listUrl + "pageNum=" + page + "\">" + page + "</a>&nbsp;");
			}
			page++;
		}
		
		//다음▶
		if(totalPage - currentPageSetup > numPerBlock) {			
			sb.append("<a href=\"" + listUrl + "pageNum=" + page + "\">다음▶</a>&nbsp;");
		}		
		return sb.toString();		
	}

 

currentPageSetup의 값을 공식으로 주었다.

if문은 위의 예외문으로 currentPage % numPerBlock == 0일 경우에 따로 설정하였다.

 

'이전' 버튼을 누를 때 전 번호 페이지로 갈 수 있도록

하이퍼링크를 통해 연결해 주었으며 이는 '다음' 버튼도 마찬가지이다.

 

또한 바로가기 페이지는

page에 시작값을 주었으며, 현재 보고 있는 페이지와 넘어가려는 페이지가 일치할 경우

해당 페이지 번호에 색깔만 주며

그 외의 번호에는 누르면 넘어갈 수 있도록 링크를 함께 연결해 준다.

 

article.jsp

마지막으로 article이다!

<%
	request.setCharacterEncoding("UTF-8");
	String cp = request.getContextPath();
	
	int num = Integer.parseInt(request.getParameter("num"));
	String pageNum = request.getParameter("pageNum");

	String searchKey = request.getParameter("searchKey");
	String searchValue = request.getParameter("searchValue");
	
	if(searchValue!=null){		
		if(request.getMethod().equalsIgnoreCase("GET")){			
			searchValue = URLDecoder.decode(searchValue,"UTF-8");			
		}		
		}else{
			searchKey = "subject";
			searchValue = ""; //null		
	}		
    
	Connection conn = DBConn.getConnection();
	BoardDAO dao = new BoardDAO(conn);
	
	dao.updateHitCount(num);
	
	BoardDTO dto = dao.getReadData(num);
	
	if(dto==null){
		response.sendRedirect("list.jsp");
	}
	
	int lineSu = dto.getContent().split("\n").length;
		
	dto.setContent(dto.getContent().replaceAll("\n", "<br/>"));
	
	String param = "";
	if(!searchValue.equals("")){
		
		param = "&searchKey=" + searchKey;
		param+= "&searchValue=" + URLEncoder.encode(searchValue, "UTF-8");
	}	
		
	DBConn.close();	
%>

 

num은 list.jsp에서 가져왔다. 추후에 조회 수 증가를 위해 가져온 것이다.

 

String searchKey부터 if문까지 검색을 위한 코딩이다.

이는 위의 list.jsp에서 본 내용과 똑같으니 참고 바란다.

 

updateHitcount는 지난 글에서 확인할 수 있듯이 BoardDAO에 입력한 조회수를 증가시키는 메서드이다.

또한 getReadData메서드를 통해 읽어온 데이터를 dto에 넣는다.

만약 dto가 null이라면, 즉 글이 없다면 redirect를 보낸다.

 

lineSu는 글의 라인 수로, 글의 내용에 엔터를 주어 줄을 나눈다.

 

String param부터 if문은 검색을 위한 코딩이며, 이 역시 list.jsp의 내용과 같다!

 

 


수정과 삭제는 BoardDAO에서 하면 되며 대표적으로 삭제 코딩을 설명하겠다.

 

public int deleteData(int num) {			
				int result = 0;			
				PreparedStatement pstmt = null;
				String sql;
				
				try {					
					sql = "delete board where num=?";				
					pstmt = conn.prepareStatement(sql);				
					pstmt.setInt(1, num);				
					result = pstmt.executeUpdate();			
					pstmt.close();				
				} catch (Exception e) {
                System.out.println(e.toString());
                }			
				return result;			
                }

수정과 삭제의 차이는 sql문에서 입력하는 것에 따라 달라진다.

num을 기준으로 삭제를 하면 되니 조건에 num을 주었다.

이 부분은 insert의 내용과도 역시 똑같다! 응용만 주면 된다.

 

 


이렇게 해서 게시판의 내용을 총정리하였다!!

페이지의 전환이 많다 보니 하나하나 신경 쓸 것도 많다.

하지만 하나하나의 코딩이 모여서 이루어진 페이지를 보니 신기하였다.

 

조금 뒤죽박죽이다 보니 블로그 글로 설명하는 것에 한계가 있었지만

작성하면서 머릿속에서 어느 정도 정리가 된 것 같다.

 

 

 

2월 16일

반응형
profile

아무튼 개발

@릴쥬

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

profile on loading

Loading...