JSP

[수업] DBCP 세팅, DBCP를 이용한 명소 리스트 출력

hs_developer 2022. 7. 22. 14:30

환경 세팅

 

commons-dbcp-1.4.jar
0.15MB
commons-pool-1.6.jar
0.11MB

 

 

 

다음 파일 다운받아서 apache tomcat 폴더에 첨부한다.


 

 

jsp 파일 생성하고 한 번 실행

 

 


 

 

DBCP 파일을 한 번 실행하면 다음 Servers 폴더가 자동 생성된다.

 

 

<Context docBase="JSPDBCProject" path="/JSPDBCProject" reloadable="true" source="org.eclipse.jst.jee.server:JSPDBCProject">
<!-- DBCP 설정 -->


<!-- Connection 저장 -->
<Resource
    drvierClassName= "oracle.jdbc.driver.OracleDriver"
    url= "jdbc:oracle:thin:@localhost:1521:XE"
    userName= "hr"
    password= "happy"
    auth= "Container"
    name= "jdbc/oracle"
    type= "javax.sql.DataSource"
    maxActive= "10"
    maxIdle= "10"
    maxWait= "-1" 
/>
</Context>

 

sever.xml의 155번 문단을 다음과 같이 수정한다. 

 

<Resource>가 <Context> 태그 안에 있어야 함!!

 

 

 


 

DBCP를 이용한 명소 리스트 출력하기

 

LocationVO.java

package com.sist.dao;
/*
NO      NOT NULL NUMBER         
TITLE   NOT NULL VARCHAR2(200)  
POSTER  NOT NULL VARCHAR2(500)  
MSG     NOT NULL VARCHAR2(4000) 
ADDRESS NOT NULL VARCHAR2(300)  
 */
public class LocationVO {
	private int no;
	private String title, poster, msg, address;
	public int getNo() {
		return no;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getPoster() {
		return poster;
	}
	public void setPoster(String poster) {
		this.poster = poster;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}

 

 

LocationDAO.java

package com.sist.dao;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
//DBCP
public class LocationDAO {
	private Connection conn;
	private PreparedStatement ps;
	
	// 연결 객체 가지고 오기 => getConnection (생성하는게 아닌 생성된 객체 가지고 옴)
	public void getConnection() 
	{
		try 
		{
			// 저장된 위치 가지고 온다 (JNDI) => java://comp/env => Connection 객체 저장
			// 1. 탐색기 열기
			Context init = new InitialContext();
			
			// 2. C드라이브 열기
			Context c = (Context)init.lookup("java://comp/env");
			// 3. 저장된 폴더에서 Connection 읽어옴
			DataSource ds = (DataSource)c.lookup("jdbc/oracle");
			conn = ds.getConnection(); // 미리 생성된 Connection 객체를 얻어옴
			
		} 
		catch (Exception e) {}
	}
	
	// 반환 => disConnection (ps.close(), conn.close() ) 쓰는거 전과 동일
	public void disConnection() 
	{
		try 
		{
			if(ps != null) ps.close();
			if(conn != null)conn.close();
			
		} catch (Exception e) {}
	}
	
	// 기능 => 전하고 동일
	public List<LocationVO> locationListData(int page)
	{
		List<LocationVO> list = new ArrayList<LocationVO>();
		
		try 
		{
			getConnection(); // 미리 생성된 Connection 객체 주소 얻어옴
			String sql = "SELECT no, title, poster, num "
					+ "FROM (SELECT no, title, poster, rownum as num "
					+ "FROM (SELECT no, title, poster "
					+ "FROM seoul_location ORDER BY no ASC)) "
					+ "WHERE num BETWEEN ? AND ?";
			
			// rownum 을 이용시 Top-n만 가능 (중간에 있는 데이터를 자르기 못함)
			ps = conn.prepareStatement(sql);
			int rowSize = 12;
			int start = (rowSize*page)-(rowSize-1);
			int end = (rowSize*page);
			ps.setInt(1, start);
			ps.setInt(2, end);
			
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()) 
			{
				LocationVO vo = new LocationVO();
				vo.setNo(rs.getInt(1));
				vo.setTitle(rs.getString(2));
				vo.setPoster(rs.getString(3));
				list.add(vo);
			}
			rs.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			disConnection(); // 닫기 => 반환 (commons-dbcp.jar) => 다른 사용자가 재사용 가능함 (일정 Connection 객체로 사용)
			
		}
		return list;
	}
	
	// 총 페이지 구하기
	public int locationTotalPage() {
		int total = 0;
		try {
			getConnection();
			String sql = "SELECT CEIL(COUNT(*)/12.0) FROM seoul_location";
			ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			rs.next();
			total = rs.getInt(1);
			rs.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			disConnection();
		}
		return total;
	}
}

 

 


 

seoul.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*, com.sist.dao.*" %>
<jsp:useBean id="dao" class="com.sist.dao.LocationDAO"/>
<%-- LocationDAO dao = new LocationDAO() --%>
<%
	// 1. page 받기
	String strPage = request.getParameter("page");
	if(strPage==null){
		strPage = "1";
	}
	int curpage = Integer.parseInt(strPage);
	
	// 현재 페이지에 대한 데이터 읽기 (DAO)
	List<LocationVO> list = dao.locationListData(curpage);
	
	// 총 페이지 구하기
	int totalpage = dao.locationTotalPage();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<style type="text/css">
.container{
	margin-top: 50px;
}
.row{
	margin: 0px auto;
	width: 960px;
}
</style>
</head>
<body>
	<div class="container">
		<div class="row">
			<%
				for(LocationVO vo : list){
			%>
					<div class="col-md-3">
				      <div class="thumbnail">
				        <a href="#">
				          <img src="<%=vo.getPoster() %>" style="width:220px; height: 150px">
				          <div class="caption">
				            <p style="font-size:9px"><%=vo.getTitle() %></p>
				          </div>
				        </a>
				      </div>
				    </div>
			<%
				}
			%>
		</div>
		<div class="row">
			<div class="text-center">
				<a href="seoul.jsp?page=<%=curpage>1?curpage-1:curpage %>" class="btn btn-sm btn-success">이전</a>
				<%=curpage %> page / <%=totalpage %> pages
				<a href="seoul.jsp?page=<%=curpage<totalpage?curpage+1:curpage %>" class="btn btn-sm btn-info">다음</a>
			</div>
		</div>
	</div>
</body>
</html>