配置连接信息

在context.xml文件的context节点下新增如下配置:

<Resource name="jdbc/test2"
    auth="Container"
    type="javax.sql.DataSource"
    username="root"
    password="xxx"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://192.168.142.129:3306/test2"
    maxActive="8"
    maxIdle="4"/>

配置数据源查询信息

在web.xml的GlobalNamingResources节点下新增如下配置:

<resource-ref>
    <description>
        Resource reference to a factory for java.sql.Connection
        instances that may be used for talking to a particular
        database that is configured in the Context
        configuration for the web application.
    </description>
    <res-ref-name>
        jdbc/test2
    </res-ref-name>
    <res-type>
        javax.sql.DataSource
    </res-type>
    <res-auth>
        Container
    </res-auth>
</resource-ref>

验证

在一个servlet中编辑如下代码

try {
    Context initCtx = new InitialContext();

    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource)envCtx.lookup("jdbc/test2");    
    Connection conn = ds.getConnection();
    Statement stmt = conn.createStatement();
    ResultSet rst = stmt.executeQuery("select uid, name from user");
    
    while (rst.next()) {
        System.out.println(rst.getString("name"));
    }
    rst.close();
    stmt.close();
    conn.close();
} catch (NamingException e1) {
    e1.printStackTrace();
} catch (SQLException e) {
    e.printStackTrace();
}

即可查询到数据。

参考:http://tomcat.apache.org/tomcat-7.0-doc/jndi-resources-howto.html