1、將連接數據庫的驅動拷貝到
Tomcat/common/lib中
2、在tomcat/conf/context.xml中配置
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- name指定數據源在容器中的JNDI名稱
maxActive指定數據源的最大活動連接數 。
maxIDle指定數據池中的最大空閑連接數。
maxWait 指定數據池中最大等待獲取連接的客戶端。
username:指定連接數據庫的連接池
password:指定連接數據庫的密碼。
driverClassName :指定連接數據庫的驅動
url指定數據庫服務的URL
-->
<Resource name="jdbc/oracleds" auth="Container" type="javax.sql.DataSource"
maxIdle="30" maxWait="10000" maxActive="10" username="dfrf" password="dfrf"
driverClassName="oracle.jdbc.OracleDriver" url="jdbc:oracle:thin:@127.0.0.1:1521:dfrf"/>
</Context>
3、使用數據源獲得數據庫連接。
Context context = new InitialContext();//初始化Context,使用InitialContext初始化Context,產生一上下文對象
//通過JNDI查找數據源,該JNDI為java:comp/env/jdbc/oracleds,分成兩部分:java:comp/env是tomcat固定的,tomcat提供的
//JNDI綁定都必須加該前綴;JDBC/oracleds是定義數據源時給數據源起的名字。
DataSource ds = (DataSource) context.lookup("java:/comp/env/jdbc/oracleds");
//獲取數據庫連接
conn=ds.getConnection();