1. 引入必要的jar包
commons-dbcp-1.2.1.jar
commons-pool-1.6.jar
ojdbc14_11g.jar
2. 配置:context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource name="iac" auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="10" maxWait="3000"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe" username="taj" password="admin" />
</Context>
name 表示指定的jndi名称
auth 表示认证方式,一般为Container
type 表示数据源床型,使用标准的javax.sql.DataSource
maxActive 最大连接数量
maxIdle 最大空闲连接
maxWait 当池的数据库连接已经被占用的时候,最大等待时间
driverClassName 、url 、username、password JDB必须的参数
3. 创建工具类:DBUtil.java
package com.utils;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBUtil {
private static DataSource dataSource;// 链接池
private static ThreadLocal<Connection> connLocal;// 线程局部变量
static {
connLocal = new ThreadLocal<Connection>();
try {
Context context=new InitialContext();
//java:/comp/env/是固定写法,后面接的是context.xml中的Resource中name属性的值
dataSource = (DataSource) context.lookup("java:/comp/env/iac");
} catch (NamingException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection conn = connLocal.get();
if (conn == null) {
conn = dataSource.getConnection();
connLocal.set(conn);
}
return conn;
}
public static void closeConnection() throws SQLException {
Connection conn = connLocal.get();
connLocal.set(null);
if (conn != null) {
conn.close();
}
}
}
4. 编写测试的jsp页面:index.jsp
<%@page import="java.sql.Connection"%>
<%@page import="com.utils.DBUtil"%>
<%@page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%
Connection conn = DBUtil.getConnection();
String str = "##"+conn+"##";
out.write(str);
conn.close();
%>
5. 然后启动tomcat进行测试:
输入地址:http://localhost:8888/tt/index.jsp
页面显示结果:
##jdbc:oracle:thin:@localhost:1521:xe, UserName=TAJ, Oracle JDBC driver##