首先注意的一点是把数据库驱动包放入tomcat\lib包中而不是放在应用程序中。
配置过程:
a.在tomcat\conf\Catalina\localhost下创建xml配置文件,名字和web项目同名
配置如下:
<Context>
<Resource name="jdbc/test" auth="Container"
type="javax.sql.DataSource"
maxActive="10" maxIdle="5" maxWait="60" username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"/>
</Context>
tomcat中context就代表一个web应用
name:数据源名称
auth:数据源的管理者-Container和Application
type:数据源所属类
maxActive:活动的最大连接数
maxIdle:空闲的最大连接数
maxWait :连接等待超时时间
username:数据库登录名
password:数据库登录密码
driverClassName:数据库驱动名
url:连接数据库URL
也可以在tomcat\conf\context.xml中添加
<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
maxActive="10" maxIdle="5" maxWait="60" username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"/>
也可以添加多个Resource。
或者在tomcat\conf\server.xml的host元素下添加
<Context path="/WebServlet" docBase="WebServlet" reloadable="true">
<Resource name="jdbc/test" auth="Container"
type="javax.sql.DataSource"
maxActive="10" maxIdle="5" maxWait="60" username="root"
password="123456"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mysql"/>
</Context>
当然也可以添加多个Context,一个Context代表一个web应用程序
context中path是指定项目的根目录,reloadable为true表示tomcat容器会监视web应用
程序中class和lib的更改去动态更新内存中的实例。
b.在tomcat\conf\web.xml中添加
<resource-ref>
<description>popuserDataSource</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
显然这个是全部应用程序可见
或者在应用程序的web.xml中做如下配置:
<resource-ref>
<description>popuserDataSource</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
res-ref-name的值必须和数据源配置中的name一样。
做这个配置是让we容器知道数据源的存在并去查找。
对于web.xml的配置在应用程序中只能为本web程序使用,而配置在tomcat文件中是可以
共享的。但是web容器是先去读取应用程序的配置的,如果没找到命名符合的信息会继
续去tomcat的web.xml中查找.
数据源的配置不论在哪个位置都是表示一个context的resource。
全部数据库配置在conf\server.xml Server元素的<globalNamingResource>下面
代码调用
Context initCtx = new InitialContext();
DataSource ds= (DataSource ) initCtx.lookup("java:comp/env/jdbc/test");