Tomcat 貌似有連接配接池管理的子產品,隻要配置了資料庫相關資訊,并告訴web應用程式,web應用程式啟動後,就可以從Tomcat那裡擷取連接配接。
1.打開apache-tomcat-7\conf\context.xml,加入資料庫資源資訊:
<Resource name="jdbc/mysource" auth="Container" type="javax.sql.DataSource"
password="sikaijian" username="root" driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost:3306/mybase"
maxActive="100" maxIdle="30" maxWait="5000"/>
2. tomcat 需要mysql的驅動程式,是以要再lib目錄中加入驅動JAR包,如:mysql-connector-java-5.1.20-bin.jar;
3.要讓web應用知道用這麼一個資料源,這麼一個連接配接池可以使用,需要在web.xml中加入如下代碼:
<resource-ref>
<description>MySQL DataSource</description>
<res-ref-name>jdbc/mysource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
完成以上三步,一個資料源就算配置完成了。
下面做了個簡單的測試,JSP片段代碼如下:
<%
try
{
Context initCtx=new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/mysource");
Connection conn=ds.getConnection();
out.println("data from database:<br>");
Statement stmt=conn.createStatement();
ResultSet rs =stmt.executeQuery("select * from staff");
%><table bordercolor="black">
<tr>
<td width="50">姓名</td>
</tr>
<%
while(rs.next())
{
%><tr><%
%><td width="50"><%out.println(rs.getString("name"));%></td><%
%></tr><%
}
%></table><%
rs.close();
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>