Servlet

DataSource를 이용한 DB 연동

dev23 2024. 8. 11. 22:21
반응형

DataSource

- 애플리케이션이 실행됨과 동시에 연동할 DB와의 연결을 미리 설정한다.

- 필요할 마다 미리 연결해 놓은 상태를 이용해 빠르게 DB 연동하여 작업한다.

- 미리 데이터베이스와 연결시킨 상태를 유지하는 기술을 커넥션풀이라고 한다.

- 톰캣 컨테이너는 자체적으로 ConnectionPool 기능을 제공하며, 톰캣 실행 시 톰캣은 설정 파일에 설정된 DB 정보를 이용해 미리 DB와 연결하여 ConnectionPool 객체를 생성한 후 애플리케이션과 연동할 일이 생기면 ConnectionPool객체의 메서드를 호출해 빠르게 연동하여 작업한다.

 

커넥션풀 동작 과정

  1. 톰캣 컨테이너를 실행한 후 응용 프로그램을 실행한다.
  2. 톰캣 컨테이너 실행 시 ConnectionPool 객체를 생성한다.
  3. 생성된 커넥션 객체는 DBMS와 연결한다.
  4. DB와의 연동 작업이 필요할 경우 응용 프로그램은 ConectionPool에서 제공하는 메서드를 호출하여 연동한다.

 

JNDI(Java Naming and Directory Interface)

- JNDI  필요한 자원을 키/값 쌍으로 저장한 후 필요할 때 키를 이용해 값을 얻는 방법이다.

- 미리 접근할 자원에 키를 지정한 애플리케이션이 실행 중일 키를 이용해 자원에 접근해서 작업을 하는 것이다.

- 실제 애플리케이션에서 ConnectionPool 객체를 구현할 때는 Java SE에서 제공하는 javax.sql.DataSource 클래스 이용한다.

- 어플리케이션 실행 톰캣이 만들어 놓은 ConnectionPool 객체에 접근할 때는 JNDI를 이용한다.

- 톰캣 컨테이너가 ConnectionPool 객체를 생성하면 객체에 대한 JNDI 이름(key) 미리 설정해 놓는다. 그러면 애플리케이션에서 DB 연동 작업을 JNDI 이름(key)으로 접근하여 작업한다.

 

톰캣 DataSource 설정 및 사용 방법

- 다음은 실제 웹 애플리케이션에서 톰캣이 제공하는 ConnectionPool 객체를 이용해 DB와 연동하는 작업이다.

  1. JDBC 드라이버를 /WEB-INF/lib 폴더에 설치한다.
  2. ConnectionPool 기능 관련 jar 파일을 /WEB-INF/lib 폴더에 설치한다.
  3. CATALINA_HOME/context.xml에 Connection 객체 생성 시 연결한 DB 정보를 JNDI로 설정한다.
  4. DAO 클래스에서 DB와 연동 시 미리 설정한 JNDI 라는 이름으로 DB와 연결해서 작업한다.

( tomcat dbcp tomcat 폴더 / lib 안의 tomcat-dbcp.jar 파일을 이용 )

tomcat 디렉터리 안에 lib 디렉터리를 확인해 보면 tomcat-jdbc.jar 파일이 존재할 것이다.

 

톰캣 DataSource 설정

- 톰캣 서버 설정 파일인 context.xml 파일을 수정한다.

 

* context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
--><!-- The contents of this file will be loaded for each web application --><Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
    
    <Resource
    	name="jdbc/mysql"
    	auth="Container"
    	type="javax.sql.DataSource"
    	driverClassName="com.mysql.jdbc.Driver"
    	url="jdbc:mysql://localhost:3306/java_web"
    	username="root"
    	password="dbpass"
    	maxActive="50"
    	maxWait="-1"
    />

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->
</Context>

 

- DB 연결 설정 속성

속성 설명
name DataSource 대한JNDI 이름
auth 인증 주체
driverClassName 연결할 DB 종류에 따른 드라이버 클래스 이름
factory 연결할 Db 종류에 따른 ConnectionPool 생성 클래스 이름
maxActive 동시에 최대로 DB 연결할 있는 Connection
maxIdle 동시에 idle 상태로 대기할 있는 최대
maxWait 새로운 연결이 생길 때까지 기다리 있는 최대 시간
user DB 접속 ID
password DB 접속 암호
type DB 종류별 DataSource
url 접속할 DB 주소와 포트 번호 SID

 

DataSource로 연동해 회원 정보 조회

* MeberDAO.java

package dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

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

import vo.MemberVO;

public class MemberDAO {

	private Connection conn;
	private PreparedStatement pstmt;
	private DataSource dataFactory;

	public MemberDAO() {
		Context ctx;
		try {
			// JNDI에 접근하기 위해 기본 경로("java:/comp/env")를 지정
			ctx = new InitialContext();
			Context envContext = (Context)ctx.lookup("java:/comp/env");
			// 톰캣 context.xml에 설정한 name 값인 jdbc/mysql을 이용해 톰캣이 미리 연결한 DataSource를 받아 옴.
			dataFactory = (DataSource)envContext.lookup("jdbc/mysql");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	public List listMembers() {
		List list = new ArrayList();
		try {
			conn = dataFactory.getConnection();	// DB에 연결
			String query = "select * from t_member ";
			System.out.println("prepareStatememt: " + query);
			pstmt = conn.prepareStatement(query);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				String id = rs.getString("id");
				String pwd = rs.getString("pwd");
				String name = rs.getString("name");
				String email = rs.getString("email");
				Date joinDate = rs.getDate("joinDate");
				MemberVO vo = new MemberVO();
				vo.setId(id);
				vo.setPwd(pwd);
				vo.setName(name);
				vo.setEmail(email);
				vo.setJoinDate(joinDate);
				list.add(vo);
			}
			rs.close();
			pstmt.close();
			conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
}

 

- DB 테이블 생성 및 레코드, MemberServlet.java, MeberVO.java 는 이전 글을 참고한다.

https://dev1023.tistory.com/71

 

서블릿 - 비즈니스 로직 처리

- 서블릿 비즈니스 처리 작업이란 서블릿이 클라이언트로부터 요청을 받으면 그 요청에 대해 작업을 수행하는 것을 의미한다.- 웹 프로그램에서 대부분의 비즈니스 처리 작업은 DB 연동 관련 작

dev1023.tistory.com

 

- 작성 후 톰캣을 재시작하고 브라우저에서 localhost:[port]/[project_name]/member 를 입력하여 접속해 본다.

조회 결과

 

반응형