這個(gè)配置弄了大概我一個(gè)上午。以前用tomcat 5.后來(lái)配置還是出了問(wèn)題,原因是很簡(jiǎn)單的一個(gè)“r”沒(méi)有寫(xiě)。
配置方法如下:
在tomcat安裝目錄下conf目錄下的context.xml加入
<Resource
name="jdbc/test" auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/lucene"
username="root" password="admin"
maxActive="30" maxIdle="10" maxWait="-1"/>
第一步好了,然后就是加入dbcp包和mysql驅(qū)動(dòng)包,2個(gè)包復(fù)制到lib目錄下。
三:修改項(xiàng)目中的web.xml文件
加入
<resource-ref>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
最后就是測(cè)試
<%@page contentType="text/html; charset=GBK"%>
<%@page import="java.sql.*" %>
<%@page import="javax.naming.*" %>
<%@page import="javax.sql.DataSource" %>
<HTML>
<HEAD>
<TITLE>JNDI測(cè)試</TITLE>
</HEAD>
<BODY>
<%
try {
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/test");
Connection conn = ds.getConnection();
out.println(conn.toString());
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
%>
</BODY>
</HTML>
如果輸出:
jdbc:mysql://localhost:3306/lucene, UserName=root@localhost, MySQL-AB JDBC Driver
這個(gè)測(cè)試不能再應(yīng)用程序中,只能在web容器中才可以。
剛測(cè)試了一下,如果想測(cè)試多個(gè)數(shù)據(jù)源的話,在context.xml要加入
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
使得數(shù)據(jù)源交由dbcpfactory管理。
如果想使用dbcp自動(dòng)回收數(shù)據(jù)庫(kù)連接資源的話,
可以在后面增加一條:
removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"
removeAbandonedTimeout 超時(shí)單位為秒,設(shè)置是需設(shè)置相當(dāng)才行