---
title: "Tomcat中如何使用数据源"
author: "ztfjava"
date: "2010-10-04T08:47:10Z"
tags: []
categories: ["企业架构"]
slug: "tomcat"
draft: false
lastmod: "2010-10-04T08:47:10Z"
id: 777047
url: "https://ztfjava.iteye.com/blog/777047"
---

本文使用的软件版本：
tomcat  5.5.15
MySql  5
Eclipse 3.1

正常情况下，配置一个数据库连接池比较简单，主要分3步：
1、在tomcat中配置一个数据源，可以通过tomcat自带的工具进行配置，配置完成后，tomcat的server.xml中会多出如下内容：
    <Resource
      name="jdbc/mysql"
      type="javax.sql.DataSource"
      password="123456"
      driverClassName="com.mysql.jdbc.Driver"
      maxIdle="20"
      maxWait="5000"
      username="root"
      url="jdbc:mysql://localhost/test"
      maxActive="10"/>

2、在某个Web应用的web.xml文件中加入如下代码：
    <resource-ref>
        <res-ref-name>jdbc/mysql</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>

3、在该Web应用的context片段中加入如下代码：
    <ResourceLink
           name="jdbc/mysql" 
           type="javax.sql.DataSource" 
           global="jdbc/mysql"/>

进行以上3处配置后，就可以使用数据库连接池了，具体试验代码如下：
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>aaaa</h1>
<%


   Context ctx=null;
   Connection cnn=null;
   Statement stmt=null;
   ResultSet rs=null;
   try
   {
    ctx=new InitialContext();
    if(ctx==null){
     out.println("1 wrong");
     throw new Exception("11");
     }
    DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/mysql");
    if(ds==null){
     out.println("2 wrong");
     throw new Exception("22"); 
     }
    
    cnn=ds.getConnection();
    stmt=cnn.createStatement();
    rs=stmt.executeQuery("select * from student");
      rs.next();
      out.println(rs.getString(2));

   }catch(SQLException e) {
    out.println(e.getSQLState());
    }
   finally
   {
    if(rs!=null)
     rs.close();
    if(stmt!=null)
     stmt.close();
    if(cnn!=null)
     cnn.close();
    if(ctx!=null)
     ctx.close();
   }
    %>
</body>
</html>

下面探讨一下在Lomboz中使用数据库连接池会出现哪些问题：
最重要的一点，他无法完成第三步配置，因为在Lomboz中启动tomcat时，他不会读取该web应用的context片段，因此，你在context片段中进行的任何配置，对于Lomboz来讲都是无效的，自然也就无法使用数据库连接池了。那么有没有解决办法呢？当然有，让我们来分析一下Lomboz启动tomcat的过程，在Lomboz中配置好一个tomcat服务器后，他会生成一个名叫Servers的项目，该项目和你的其他Eclipse项目位于同一个目录，很好找。进入Servers文件夹，你会看见一个名叫Tomcat v5.5 Server @ localhost-config的文件夹，进入该文件夹你会找到一个server.xml文件，这个文件就是在Lomboz中启动tomcat所用到的配置文件，他不会使用位于tomcat目录下的配置文件。因此要想使你的配置对于Lomboz有效，你就应该修改这个文件。最后再说一点重要的，对这个文件的修改不可以通过一般的编辑软件进行，必须使用Eclipse自带的XML编辑器进行，否则在Lomboz中将无法启动tomcat。
最后给出一个修改好的例子，红色部分为被修改处，仅供参考：
<?xml version="1.0" encoding="UTF-8"?>
<Server>
  <Listener className="org.apache.catalina.core.AprLifecycleListener"/>
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
  <Listener className="org.apache.catalina.storeconfig.StoreConfigLifecycleListener"/>
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
  <GlobalNamingResources>
    <Environment
      name="simpleValue"
      type="java.lang.Integer"
      value="30"/>
    <Resource
      auth="Container"
      description="User database that can be updated and saved"
      name="UserDatabase"
      type="org.apache.catalina.UserDatabase"
      pathname="conf/tomcat-users.xml"
      factory="org.apache.catalina.users.MemoryUserDatabaseFactory"/>
    <Resource
      name="jdbc/mysql"
      type="javax.sql.DataSource"
      password="123456"
      driverClassName="com.mysql.jdbc.Driver"
      maxIdle="20"
      maxWait="5000"
      username="root"
      url="jdbc:mysql://localhost/test"
      maxActive="10"/>
  </GlobalNamingResources>
  <Service name="Catalina">
    <Connector connectionLinger="-1" connectionTimeout="60000" maxHttpHeaderSize="8192" maxSpareThreads="75" maxThreads="150" minSpareThreads="25" port="80" redirectPort="8443" serverSoTimeout="0" tcpNoDelay="true">
    </Connector>
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443">
    </Connector>
    <Engine defaultHost="localhost" name="Catalina">
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"/>
      <Host appBase="webapps" name="localhost">
      <Context docBase="E:\java程序\addbook\.deployables\addbook" path="/addbook" privileged="true" reloadable="true">
          <ResourceLink
               name="jdbc/mysql" 
               type="javax.sql.DataSource" 
               global="jdbc/mysql"/>
      </Context><Context docBase="E:\java程序\myweb\.deployables\myweb" path="/myweb" reloadable="true" source="com.ibm.wtp.web.server:myweb"/> <Context docBase="E:\java程序\StrutsTest\.deployables\StrutsTest" path="/StrutsTest" reloadable="true" source="com.ibm.wtp.web.server:StrutsTest"/><Context docBase="E:\MyWeb" path="/aa" reloadable="true"/></Host>
    </Engine>
  </Service>
</Server> 

本文来自CSDN博客，转载请标明出处：http://blog.csdn.net/andycpp/archive/2006/04/14/663642.aspx