首先按照tomcat文档的描述,我做了如下配置:
1 建立名为cloth的数据库,建立一个表----testdata。建一名为register的工程,工程的WebRoot路径为E:/workplace/register/WebRoot
2 打开Tomcat 5.5/conf下的server.xml,在<host>标记对内添加如下内容(关键):
<Context path="/register"
docBase="E:/workplace/register/WebRoot"
debug="5"
reloadable="true" crossContext="true">
<Resource name="jdbc/cloth" --------------------可自定义名称
auth="Container"
type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="123" ------------------------数据库管理员信息
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/cloth?autoReconnect=true"/>
</Context>
3 在web.xml中的<web-app>标签内做如下配置:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/cloth</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4 页面内运用建立index.jsp
<%
try{
java.sql.Connection con;
Statement stmt;
ResultSet rs;
Context ctx = new InitialContext();
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/cloth");
con=ds.getConnection();
stmt=con.createStatement();
rs=stmt.executeQuery("select * from testdata");
while(rs.next()){
out.println(rs.getString(1)+"--"+rs.getString(2));
}
rs.close();
stmt.close();
con.close();
}catch(Exception e){
out.print(e.getMessage());
}
%>
一般情况下可以得到所需的效果,连接成功。但是电脑有时候就是发神经,经常给你出错,也许会报一下错误:
@ Cannot load JDBC driver class 'com.microsoft.jdbc.sqlserver.SQLServerDriver'
@@ Connection to pool failed!---javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
@@@ Cannot create PoolableConnectionFactory ([Microsoft][SQLServer 2000 Driver for JDBC]Unable to connect. Invalid URL.)
这时候请仔细检查数据源的名称,管理员密码,以及web.xml中的配置是否正确。
如果出现Cannot create JDBC driver of class '' for connect URL 'null',那么在
Tomcat 5.5/conf/Catalina/localhost下建立register(工程名).xml,内容为:
<Context path="/register" docBase="E:/workplace/register/WebRoot" >
<ResourceLink name="jdbc/cloth" type="javax.sql.DataSource" global="jdbc/cloth"/>
</Context>
主要就是解决的这个global的问题,具体也解释不清了。
按照上面所述配置,应该可以很简单解决数据源配置中出现的问题了。