首先是再WebRoot 下的 META-INF目录下建立一个 context.xml。
然后是配置context.xml:
<span style="color:#ff0000;"><?xml version="1.0" encoding="UTF-8"?>
<context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource
name = "jdbc/worksy"
author = "Container"
type = "javax.sql.DataSource"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost:3306/worksy"
username = "root"
password = "123"
maxActive = "80"
maxldle = "20"
maxWait="3000"
/>
</context></span>
然后配置: web.xml
<resource-ref>
<res-ref-name>jdbc/worksy</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
然后在Servlet里写测试代码:
<pre name="code" class="java">//获得数据库的链接
public Connection getDataBaseCon() throws Exception{
Context initCon = new InitialContext();
Context ctx = (Context)initCon.lookup("java:/comp/env");
DataSource dataSource = (DataSource)ctx.lookup("jdbc/worksy");
Connection con = dataSource.getConnection();
return con;
}
异常:不能创建类为这个URL,或者 URL是NULL 的。检查配置文件都没有错误的话。就是Servlet里的代码问题了。注意上面Servlet里的写法。