配置Tomcat连接池

cwf8 9年前

配置Tomcat连接池

首先在Tomcat7下面的conf/context.xml中的<context>标签中添加属性:

<Resource            name="jdbc/imooc"            auth="Container"            type="javax.sql.DataSource"           maxActive="100"            maxIdle="30"            maxWait="10000"           username="root"            password="123456"            driverClassName="com.mysql.jdbc.Driver"           url="jdbc:mysql://localhost:3306/test"    />

然后在项目中的web.xml中的<web-app>添加如下配置:

<description>MySQL Test App</description>      <resource-ref>          <description>DB Connection</description>          <res-ref-name>jdbc/imooc</res-ref-name>          <res-type>javax.sql.DataSource</res-type>          <res-auth>Container</res-auth>      </resource-ref>

值得注意的是Tomcat中的name必须和web.xml中的<res-ref-name>jdbc/imooc</res-ref-name>
保持一致。

Jsp页面调用

<%@ page contentType="text/html; charset=UTF-8" %>    <%@ page import = "javax.naming.*,java.sql.*,javax.sql.*" %>    <%     String result="";     String test="";     Context initContext = new InitialContext();     Context envContext = (Context)initContext.lookup("java:/comp/env");     DataSource ds = (DataSource)envContext.lookup("jdbc/imooc");     Connection conn = ds.getConnection();     Statement stmt = conn.createStatement();     ResultSet rs = stmt.executeQuery("select * from imooc_goddess");     while(rs.next()){      result +="\n 第一字段内容:" + rs.getString(2)+"<br>";     }     conn.close();    %>    <%=result %>

上面的相对应的代码也可以

Context initContext = new InitialContext();     DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/imooc");

但是推荐使用第一种方式。。

原因见:http://blog.csdn.net/tony8829/article/details/7252651