server.xml的修改我推荐使用tomcat的admin组件完成,完全图形化配置,相当容易。或者按下面的写法在< globalnamingresources>< /globalnamingresources>之间写如下配置(仅供参考,各位用的时候,请改成自己数据库的配置):
<resource
name="jdbc/mysql"
type="javax.sql.datasource"
password="******"
driverclassname="org.gjt.mm.mysql.driver"
maxidle="2"
maxwait="5000"
username="root"
url="jdbc:mysql://127.0.0.1/test"
maxactive="4" />
然后,在tomcat安装目录下/conf/catalina/localhost文件夹中建立一个和你网站文件夹名字一样的xml文件。例如:testsourse.xml。内容如下:
<?xml version="1.0" encoding="utf-8"?>
<context>
<resource
name="jdbc/mysql"
type="javax.sql.datasource"
password="******"
driverclassname="org.gjt.mm.mysql.driver"
maxidle="2"
maxwait="5000"
username="root"
url="jdbc:mysql://127.0.0.1/test"
maxactive="4" />
</context>
其实就是把server.xml的内容再重复一遍。这一步非常重要,如果没有这步就会出错,会出现 org.apache.tomcat.dbcp.dbcp.sqlnestedexception: cannot create jdbc driver of class '' for connect url 'null'错误。
最后,在你自己网站的/web-inf/web.xml文件中,添加一下代码(参考):
<resource-ref>
<description>db connection</description>
<res-ref-name>jdbc/mysql</res-ref-name>
<res-type>javax.sql.datasource</res-type>
<res-auth>container</res-auth>
</resource-ref>
ok。配置全部完成。现在你可以写代码测试这个数据库连接池了。如:
datasource ds = null;
initialcontext ctx = new initialcontext();
ds = (datasource) ctx.lookup("java:comp/env/jdbc/mysql");
connection conn = ds.getconnection();
数据库连接对象得到了。
如对本文有疑问,
点击进行留言回复!!
网友评论