??摘錄地址:
http://www.mylinux.com.cn/newsTextAction.do?id=8,082在網上尋找Tomcat的數據庫連接池的配置方法,忙碌了一上午,終于弄成功了,呵呵
操作系統:windows XP SP1
1.安裝JDK 5.0 update 1
下載:http://java.sun.com/
假設安裝路徑為 D:\Java\jdk1.5.0_01
設置環境變量(控制面板->系統->高級)
JAVA_HOME=D:\Java\jdk1.5.0_01
classpath=.;D:\Java\jdk1.5.0_01\lib\dt.jar;D:\Java\jdk1.5.0_01\lib\tools.jar;
path=path;%JAVA_HOME%\bin
2.安裝Tomcat 5.5.4
下載:http://jakarta.apache.org/site/binindex.cgi
(http://apache.freelamp.com/jakarta/tomcat-5/v5.5.4/bin/jakarta-tomcat-5.5.4.exe)
安裝到d:\tomcat 5.5,安裝Tomcat 5.5需要 JRE 5.0 ,安裝過程中如果沒有自動識別第一安裝的jdk5.0的路徑,需要手動指定JRE5.0的路徑.
設置環境變量
CATALINA_HOME=D:\Tomcat 5.5
-------------------------------------------
配置D:\Tomcat 5.5\conf\server.xml
-------------------------------------------
在<host></host>之間加上下面的配置信息
<Context path="/DBTest" docBase="D:/DBTest" debug="1" reloadable="true">
? <Resource name="jdbc/connectDB" auth="Container"
??? type="javax.sql.DataSource"
??? driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
??? url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=test" username="sa"
??? password="password" maxActive="20" maxIdle="10" maxWait="-1" />
</Context>
其中path設置虛擬目錄的名字,docBase為系統中的實際路徑
<Resource>里配置了連接池的相關參數
注意將SQL Server的JDBC驅動(msutil.jar,msbase.jar,mssqlserver.jar)放到D:\Tomcat 5.5\common\lib或者D:\DBTest\WEB-INF\lib目錄下
D:\DBTest的目錄結構
???? |-----WEB-INF----web.xml
????????????????????????? ?|-----classes
?????????????????????????? |-----lib
-------------------------------------------
配置D:\DBTest\WEB-INF\web.xml
-------------------------------------------
在<web=app></web-app>之間加上
<resource-ref>
<description>connectDB</description>
<res-ref-name>jdbc/connectDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
配置好后重新啟動Tomcat
-----------------------------------------
JSP測試代碼D:\DBTest\testdb.jsp
-----------------------------------------
<%@ page contentType="text/html; charset=GBK"%>
<%@ page import="java.sql.*,javax.sql.DataSource,javax.naming.*"%>
<html>
<head><title>DBCP</title></head>
<body bgcolor="#ffffff">
<h1>test Tomcat</h1>
<%
try
{
Context initCtx=new InitialContext();
DataSource ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/connectDB");
Connection conn=ds.getConnection();
Statement stmt=conn.createStatement();
ResultSet rs =stmt.executeQuery("select * from test");
?while(rs.next()) {%>
??? First:<%=rs.getString(1)%>
??? <%}%>
?? <%out.print("Successful!\n");%>??
<%
rs.close();
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>
注意先在sql server中建好相應的測試數據
好了,現在在瀏覽器中訪問http://localhost:8080/DBTest/testdb.jsp,大功告成