jsp db connection 설정 (datasource)

라이브러리

1
2
3
4
commons-collections4-4.1.jar
commons-dbcp2-2.1.1.jar
commons-pool2.2.4.2.jar
mysql-connector-java-5.1.44-bin.jar

4개 파일 다운 후 WebContent/WEB-INF/lib에 복사

mysql connector는

프로젝트 web.xml 생성

프로젝트 우클릭 - Java EE Tools - Generate Deployment Descriptor Stub -> WebContent/WEB-INF/web.xml 생성 확인

아래 내용 추가

1
2
3
4
5
6
<!-- web.xml -->
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-auth>Container</res-auth>
</resource-ref>

톰캣 서버 context.xml 설정

1
2
3
4
5
6
7
8
9
10
11
12
<!-- context.xml -->
<Resource name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="userpass"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://hostname:port/dbname"/>
<!—- 빨간글씨는 바꿔야 하는 부분 —->

dao 생성자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BDao {
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;

public BDao(){
try{
Context init = new InitialContext();
Context env = (Context)init.lookup("java:comp/env");
DataSource ds = (DataSource)env.lookup("jdbc/mysql");
connection = ds.getConnection();
System.out.println("db connection success!!");
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 각 method 에서 connection, ps, rs 를 close() 해주는 것을 잊지 말자

주의사항

mysql connector는 소스쪽과 서버쪽 폴더 동시에 적용시켜야한다.(복사)

  • 위와 같이 했음에도 아래와 같이 에러가 나는 경우
    • 심각: Servlet.service() for servlet [com.javalec.ex.frontcontroller.BFrontContrller] in context with path [/first_test] threw exception [Servlet execution threw an exception] with root cause
    • 위에설치한 4개의jar파일중 버전이 맞지 않아서 생기는 에러(ex. mysql-connector-java-5.1.44-bin.jar이 낮아서 생기는 에러였음)
  • 최신버전으로 다운로드 후 다시 WebContent/WEB-INF/lib에 복사
  • 아파치 톰캣 설치한 경로에도 mysql-connector jar파일을 복사해주어야 한다.