本配置方法来源于网络,在自己调试过程中对其进行了一定的调整,存放于本博客以便后续使用时查阅,如有不对的,请指教
1、把数据库JDBC驱动拷贝到%TOMCAT_HOME%/common/lib和Eclipse工程的WebContent/web-inf/lib下
2、在Eclipse的服务器的server.xml的web程序的节点:
<Context docBase="FileManager" path="/FileManager" reloadable="true" source="org.eclipse.jst.j2ee.server:FileManager">
</Context>
之间添加如下内容:
<Resource name="jdbc/filedb" auth="Container"
type="javax.sql.DataSource" maxActive="100" maxIdle="30"
maxWait="10000" username="sa" password="123"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:shaird" />
SQLServer的驱动名: com.microsoft.jdbc.sqlserver.SQLServerDriver
URL: jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=filedb
其中, FileManager 是你的应用的名字,到Server.xml中要寻找你的应用;
3、在%TOMCAT_HOME%/conf/Catalina/localhost下新建一个与你web文件夹同名的xml文件(我的是FileManager.xml)
这一步非常重要,如果没有这步就会出错,会出现org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' 这样的错误,在文件中加入第2步的内容,如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/filedb" auth="Container"
type="javax.sql.DataSource" maxActive="100" maxIdle="30"
maxWait="10000" username="sa" password="123"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:shaird" />
</Context>
4、修改Eclipse工程的WebContent/web-inf下的web.xml 在</web-app>之前加入下面的内容:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/filedb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
5、测试 在WebContent下新建一个DBTest.jsp 文件。
<%@page contentType="text/html;charset=gbk"%>
<%@page import="java.sql.*"%>
<%@page import="javax.sql.*" %>
<%@page import="javax.naming.*" %>
<%
try {
Context initContext = new InitialContext();
Context envContext =
(Context)initContext.lookup("java:/comp/env");
DataSource ds =
(DataSource)envContext.lookup("jdbc/filedb");
Connection conn = ds.getConnection();
if(!conn.isClosed())
out.println("数据库连接测试成功");
conn.close();
}
catch(SQLException e) {
out.println(e.toString());
}
%>
红色为你在XML中驱动的名字