在您的WEB工程的META-INF目录里新建一个context.xml内容为(以mysql为例):
<Context debug="0">
<Resource
auth="Container"
name="jdbc/mydb"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
password="您的密码"
maxIdle="15"
maxWait="10000"
username="您的用户名"
url="jdbc:mysql://localhost:3306/您的数据库名"
logAbandoned="true"
removeAbandonedTimeout="60"
maxActive="5"/>
</Context>
然后在你的web.xml里添加
<resource-ref>
<res-ref-name>jdbc/mydb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
当您需要进行数据操作时,调用以下方法得到数据库连接
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mydb");
Connection conn = ds.getConnection();