본문 바로가기

Program/JSP

페이징, Connection Pool(중립용)

22.08.23 - 페이징, Connection Pool(중립용)

페이징


  • 코드

      <%@ page contentType="text/html;charset=UTF-8"%>
      <%
          int totalRecord = 26;//모든 레코드 수 
          int pageSize = 10; //한 페이지당 보여질 레코드 수 
          int totalPage = (int)Math.ceil((float)totalRecord/pageSize); 
          int blockSize = 10;//한 블럭당 보여질 페이지 수 
          int currentPage =1;
          if(request.getParameter("currentPage")!=null){
              currentPage = Integer.parseInt(request.getParameter("currentPage")); //현재 페이지 
          }
          int firstPage=currentPage-(currentPage-1)%blockSize;//블럭당 시작 페이지
          int lastPage=firstPage+(blockSize-1);//블럭당 마지막 페이지
    
          //페이지당 시작 번호
          int num = totalRecord-(currentPage-1)*pageSize;
      %>
      <%="totalRecord는 " + totalRecord+"<br>" %>
      <%="pageSize는 " + pageSize+"<br>" %>
      <%="totalPage " + totalPage+"<br>" %>
      <%="blockSize " + blockSize+"<br>" %>
      <%="currentPage " + currentPage+"<br>" %>
      <!DOCTYPE html>
      <html>
      <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <style>
      table {
          border-collapse: collapse;
          border-spacing: 0;
          width: 100%;
          border: 1px solid #ddd;
      }
    
      th, td {
          text-align: left;
          padding: 16px;
      }
    
      tr:nth-child(even) {
          background-color: #f2f2f2;
      }
      .page-style{
          font-size:20px;
          font-weight:bold;
          color:red;    
      }
      a{text-decoration : none;}
      </style>
      </head>
      <body>
          <table>
              <tr>
                  <th width="5%">No</th>
                  <th width="70%">기사 제목</th>
                  <th width="5%">작성자</th>
                  <th width="10%">작성일</th>
                  <th width="5%">조회수</th>
              </tr>
              <!-- 하나의 페이지에 너무 많은 데이터가 있을 경우, 원하는 크기로 분리하여 보여주는 기법을 페이징(Paging)처리라고 하는데
              이는 데이터에 대한 산수계산 이므로 개발자가 로직을 개발해야함 -->
              <%for(int i=1;i<=pageSize;i++){ %>
              <%if(num<1)break; %>
              <tr>
                  <td><%=num-- %></td>
                  <td>Smith</td>
                  <td>50</td>
                  <td>50</td>
                  <td>50</td>
              </tr>
              <%} %>
              <tr>
                  <td colspan="5" style="text-align:center">
                  <%if(firstPage-1>0){ %>
                      <a herf="/news/list.jsp?currentPage=<%=firstPage-1%>">◀</a>
                      <%}else{ %>
                      <a herf="javascript:alert('이전 페이지가 없습니다.');">◀</a>
                      <%} %>
                  <%for(int i=firstPage; i<=lastPage; i++){ %>
                  <%if(i>totalPage)break;//총 페이지 수를 넘어셔면 빠져나옴 %>
                  <a href="/news/list.jsp?currentPage=<%=i%>"<%if(i==currentPage){ %> class="page-style"<%} %>>[<%=i%>]</a>
                  <%} %>
                      <%if(lastPage+1 < totalPage){ %>
                      <a herf="/news/list.jsp?currentPage=<%=lastPage+1%>">▶</a>
                      <%}else{ %>
                      <a herf="javascript:alert('이전 페이지가 없습니다.');">▶</a>
                      <%} %>
                  </td>
              </tr>
              <tr>
                  <td colspan="5"><button onClick="locatoin.href='/news/regist.jsp';">뉴스작성</button></td>
              </tr>
          </table>
    
      </body>
      </html>

Connection Pool(중립용)


  • 코드

      package com.aca.web0812.news;
    
      import java.io.IOException;
      import java.sql.Connection;
      import java.sql.PreparedStatement;
      import java.sql.SQLException;
    
      import javax.naming.InitialContext;
      import javax.naming.NamingException;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.sql.DataSource;
    
      //뉴스 기사 등록 요청을 처리하는 서블릿
      public class RegistServlet extends HttpServlet{
    
          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              //날아온 파라미터를 받아서  DB에 넣기
              request.setCharacterEncoding("utf-8");
              String title = request.getParameter("title");
              String writer = request.getParameter("writer");
              String content = request.getParameter("content");
              Connection con = null;
              try {
                  InitialContext context= new InitialContext();//JNDI 검색 객체
                  DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/myoracle");//암기사항 env까지 그 뒤는 server.xml파일의 name 사용 
    
                  //Connection Pool로 부터 Connection추출
                  con = ds.getConnection();
                  String sql = "INSERT INTO news(news_id,title, writer, content) VALUES(seq_news.nextval,?,?,?)";
                  PreparedStatement pstmt = con.prepareStatement(sql);
                  pstmt.setString(1, title);
                  pstmt.setString(2, writer);
                  pstmt.setString(3, content);
    
                  int result =pstmt.executeUpdate();//쿼리 수행
    
    
        } catch (NamingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if(con!=null) {
                try {
                    con.close();//Connection을 닫는 거는 아니고 Pool에 돌려보내는거
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


    }
}
```