JSP + Servlet | MVC 패턴(모델 2) 게시판 구현 6/n - 페이징

파과·2022년 7월 27일
0
post-custom-banner

BoardListAction.java

package com.sw.controller.action;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sw.dao.BoardDAO;
import com.sw.dto.BoardVO;

public class BoardListAction implements Action {

	//Action 인터페이스를 구현했으므로 execute()를 오버라이딩한다. 
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String url = "/board/boardList.jsp";
		
		//DAO 객체 생성
		BoardDAO bDao = BoardDAO.getInstance();
		
		//---------------------------------------------page start
		int page = 1; //처음에는 무조건 1페이지가 실행되도록
		int limit = 10; //한 페이지에 보이는 최대 게시글 개수
		
		//값이 넘어오면 null이 아니고, 값을 선택한 적이 없으면 null → 여기 정해둔 대로 page값이 1.
		if(request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
			
		//페이징을 위해 전체 레코드(글) 개수를 조회해줄 메소드를 DAO에서 가져와 사용할 것
		int listcount = bDao.getListCount();
		
		//getBoardList: 현재 선택된 번호를 기준으로 10개의 레코드를 조회하는 메소드
		List<BoardVO> boardList = bDao.getBoardList(page, limit);
		
//		int maxpage = (int)((double)listcount / 10 + 0.95);
//		int startpage = (((int)((double)page / 10 + 0.9)) -1) * 10 + 1;
//		//startpage와 startrow 같게 써도 됨.. startrow가 훨씬 간단..
//		int endpage = startpage + 10 - 1;
		
		int maxpage = (listcount %  limit) != 0 ? (listcount/limit) + 1 : (listcount/limit);
	      int startpage = ((int)((double)page/limit + 0.9)-1)*limit+1;
	      int endpage = startpage + limit -1;

		
		if(endpage > maxpage) {                                                                            
		    endpage = maxpage;                                                                               
		}    
				
		//---------------------------------------------page end
		
		//게시판정보를 VO객체의 리스트로 저장
		//List<BoardVO> boardList = bDao.selectAllBoards(); 여기서는 대신 bDao.getBoardList사용!
		//요청에 boardList속성으로 담아 보냄
		request.setAttribute("boardList", boardList);
		request.setAttribute("maxpage", maxpage);
		request.setAttribute("startpage", startpage);
		request.setAttribute("endpage", endpage);
		request.setAttribute("listcount", listcount);
		request.setAttribute("page", page);
		
		//boardList.jsp로 요청 전달
		RequestDispatcher dispatcher = request.getRequestDispatcher(url);
		dispatcher.forward(request, response);
	}

	
}

boardList.jsp

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

<%
int listcount = (Integer)(request.getAttribute("listcount"));
int nowpage = (Integer)(request.getAttribute("page"));
int maxpage = (Integer)(request.getAttribute("maxpage"));
int startpage = (Integer)(request.getAttribute("startpage"));
int endpage = (Integer)(request.getAttribute("endpage"));
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="css/shopping.css">
</head>
<body>
<div id="wrap" align="center">
<h1>게시글 리스트</h1>
<table class="list">
   <tr>
      <td colspan="5" style="border:white; text-align:right">
         <a href = "BoardServlet?command=board_write_form">게시글 등록</a>
      </td>
   </tr>
   <tr>
    <th>번호</th><th>제목</th><th>작성자</th><th>작성일</th><th>조회</th>
   </tr>
   <c:forEach var="board" items = "${boardList}">
      <tr class="record">
         <td>${board.num}</td>
         <td><a href="BoardServlet?command=board_view&num=${board.num}">${board.title}</a></td>
         <td>${board.name}</td>
         <td><fmt:formatDate value="${board.writedate}" /></td>
         <td>${board.readcount}</td>
      </tr>
   </c:forEach>
   <!-- 페이지 번호 시작 -->
   <tr align="center" height="20">
      <td colspan="5">
      <%if(nowpage <= 1){ %>
      [이전] &nbsp;
      <%}else{%>
      <a href="BoardServlet?command=board_list&page=<%= nowpage-1 %>">[이전]</a>&nbsp;
      <%}%>
      
      <%
         for(int a= startpage;a<=endpage;a++){
            if(a == nowpage){
      %>
         [<%= a %>]      
            <%}else{%>
            <a href="BoardServlet?command=board_list&page=<%= a %>">[<%= a %>]</a>&nbsp;
         <%}%>
      <%}%>

      <% if(nowpage >= maxpage){ %> 
      [다음]
      <%} else { %>
      <a href="BoardServlet?command=board_list&page=<%= nowpage+1 %>">[다음]</a>&nbsp;
      <%}%>
      </td>
   </tr>
</table>
</div>
</body>
</html>

BoardDAO.java에 추가

//페이징을 위해 레코드 개수 세는 메소드
	public int getListCount() {
		
		int x = 0; //전체 글의 개수를 담을 변수
		String sql = "select count(*) from board";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DBManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()) {
				x = rs.getInt(1);
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(conn, pstmt, rs);
		}
		return x;
	}
	
	public List<BoardVO> getBoardList(int page, int limit){
		//sql문 작성시 " " 공백 꼭 작성!
		String sql = "select * from "
				+ "(select rownum rnum, num, name, "
				+ "email, pass, title, content, "
				+ "readcount, writedate from "
				+ "(select * from board order by writedate desc)) "
				+ "where rnum >= ? and rnum <= ?";	
		
		//ex
		//page 1 → 1 ~ 10
		//page 2 → 11 ~ 20
		//page 3 → 21 ~ 30
		
		List<BoardVO> list = new ArrayList<BoardVO>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		int startrow =  (page - 1) * 10 + 1;
		int endrow = startrow + limit - 1;
		
		try {
			conn = DBManager.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, startrow);
			pstmt.setInt(2, endrow);
			rs = pstmt.executeQuery();
			
			while(rs.next()) {
				BoardVO bVo = new BoardVO();				
				bVo.setNum(rs.getInt("num"));
				bVo.setName(rs.getString("name"));
				bVo.setEmail(rs.getString("email"));
				bVo.setPass(rs.getString("pass"));
				bVo.setTitle(rs.getString("title"));
				bVo.setContent(rs.getString("content"));
				bVo.setReadcount(rs.getInt("readcount"));
				bVo.setWritedate(rs.getTimestamp("writedate"));
				list.add(bVo);
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}finally {
			DBManager.close(conn, pstmt, rs);
		}
		return list;

	}
post-custom-banner

0개의 댓글