Tomcat本身并没有提供数据源的实现。但借助其他一些开源的数据源实现,Tomcat可提供容器对其进行管理,程序可通过JNDI查找获得数据源。
Tomcat数据源的配置分为两种:
全局数据源:对所有的web应用都可以访问。
局部数据源:只能在某个web应用下访问。
下面开始配置
Step by Step:
1。将数据库驱动程序拷贝到tomcat/common/lib目录下面。
另,开源数据源依赖的jar文件也要拷到该目录下。
2。若配置全局数据源,修改conf/server.xml文件,如下:
<
Resource
name
="jdbc/TestDB"
auth
="Container"
type
="javax.sql.DataSource"
maxActive
="100"
maxIdle
="30"
maxWait
="10000"
username
="root"
password
="123456"
driverClassName
="com.mysql.jdbc.Driver"
url
="jdbc:mysql://127.0.0.1:3306/test"
characterEncoding
=GBK&useUnicode=TRUE"/>
<
resource-ref
>
<
description
>
DB Connection
</
description
>
<
res-ref-name
>
jdbc/TestDB
</
res-ref-name
>
<
res-type
>
javax.sql.DataSource
</
res-type
>
<
res-auth
>
Container
</
res-auth
>
</
resource-ref
>
Context ctx
=
new
InitialContext();
DataSource ds
=
ctx.lookup(
"
java:comp/env/jdbc/TestDB
"
);
Connection conn
=
ds.getConnection();
Statement stmt
=
conn.createStatement();
ResultSet rs
=
stmt.executeQuery(
"
select * from newsinf
"
);
while
(rs.next())

...
{
//............,
}
Tomcat数据源的配置分为两种:
全局数据源:对所有的web应用都可以访问。
局部数据源:只能在某个web应用下访问。
下面开始配置
Step by Step:
1。将数据库驱动程序拷贝到tomcat/common/lib目录下面。
另,开源数据源依赖的jar文件也要拷到该目录下。
2。若配置全局数据源,修改conf/server.xml文件,如下:






注意的是:如果有&字符,需要转移成&(XML文件规范)。不推荐配置全局数据源。
若配置局部数据源,则只需修改特定web应用下的配置文件,在Context配置节点内加上资源节点,同配置全局数据源类似,只是修改文件不同。
3。修改Web应用WEB-INF/web.xml文件,加上Resource-Def,如下:






4。重新启动Web应用,在Web应用中可以通过下面的代码来获取数据源和数据库连接:









