在TOMCA下的Catalina\localhost目录的工程xml,编写如下代码:
<Context path="/testProject" docBase="E:\project\TestProject\WebContent" reloadable="true" debug="0" privileged="true">
<Resource name="jdbc/mysql" auth="Container" type="javax.sql.DataSource"/>
<ResourceParams name="jdbc/mysql">
<parameter>
<name>factory</name>
<value>org.apache.commons.dbcp.BasicDataSourceFactory</value>
</parameter>
<parameter>
<name>maxWait</name>
<value>5000</value>
</parameter>
<parameter>
<name>maxActive</name>
<value>20</value>
</parameter>
<parameter>
<name>password</name>
<value>password</value>
</parameter>
<parameter>
<name>url</name>
<value>jdbc:mysql://localhost:3306/mysql</value>
</parameter>
<parameter>
<name>driverClassName</name>
<value>com.mysql.jdbc.Driver</value>
</parameter>
<parameter>
<name>maxIdle</name>
<value>10</value>
</parameter>
<parameter>
<name>username</name>
<value>root</value>
</parameter>
</ResourceParams>
</Context>
在工程目录WebContent\WEB-INF下的web.xml中添加:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
java代码实现:
InitialContext initctx=new InitialContext();
Context ctx= (Context) initctx.lookup("java:comp/env");
DataSource ds=(DataSource)ctx.lookup("jdbc/mysql");
Connection cn = ds.getConnection();
Statement st = cn.createStatement();