弄了大半天,終於把tomcat5.5配置資料來源的操作弄清除,其實也挺簡單的幾步
tomcat5.5 串連mysql5.0 a. 找到tomcat的server.xml檔案,在 </Host>前面加上資料來源的設定檔:具體為:<Context path="/mysql" docBase="mysql"reloadable="true" crossContext="true" debug="0" >
<Resource name="jdbc/mysql"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="root"
password="hailang43"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test?useUnicode=true"/>
</Context>其中紅色部分的path和docBase為使用該資料來源的工程的名字。 b.在工程所在目錄的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>注意代碼加在</web-app>之前。 c.將mysql的驅動放到工程所在的lib目錄中,用一個jsp檔案來驗證是否串連成功如下:<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Test of Tomcat connection pool</title>
</head>
<body>
<%
out.print("strat test connection pool!<br/>");
try{
Context initCtx = new InitialContext();
Context ctx = (Context) initCtx.lookup("java:comp/env");
Object obj = (Object) ctx.lookup("jdbc/mysql");
DataSource ds = (javax.sql.DataSource)obj;
Connection conn = ds.getConnection();
out.print("tomcat mysql connection pool runs perfectly!<br/>");
out.print("The conn is : "+conn);
conn.close();
}
catch(Exception ex){
out.print(ex.getMessage());
ex.printStackTrace();
}
%>
</body>
</html>如果輸出為不報錯就OK了。
附註串連sql2000的代碼web.xml: <resource-env-ref>
<description>sql2k Connection</description>
<resource-env-ref-name>jdbc/sql2k</resource-env-ref-name>
<resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref> server.xml: <Context path="/sql2k" docBase="sql2k" reloadable="true" crossContext="true" debug="0" >
<Resource name="jdbc/sql2k"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="sa"
password="hailang43"
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"
url="jdbc:microsoft:sqlserver://localhost:1433"/>
</Context>這裡的url後面加上useUnicode=true就會報錯,請注意一下,我也不知道為什麼。 測試jsp<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Test of Tomcat connection pool</title>
</head>
<body>
<%
out.print("strat test connection pool!<br/>");
try{
Context init=new InitialContext();
Context envContext = (Context)init.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/sql2k");
Connection conn = ds.getConnection();
out.print("tomcat mysql connection pool runs perfectly!");
conn.close();
}
catch(Exception ex){
out.print(ex.getMessage());
ex.printStackTrace();
}
%>
</body>
</html> OK,寫完了。希望能對大家有所協助!!!