我用的建立虚拟目录的方法:
在Tomcat 6.0\conf\Catalina\localhost(要是没有这个localhost你就自己建一个,我用的install版的,安装模式full,自带这个目录)下建立自己站点的context.xml
配置如下:在context元素中设置属性 docBase="你的站点绝对路径地址,第一层目录" 正常是<Context docBase="地址" />但是后来加了数据源就有了改动
<?xml version="1.0" encoding="UTF-8"?> <Context docBase="d:/UserManage"> <Resource name="jdbc/lhdb" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="1000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/lhdb" /> </Context>
启动tomcat,你会看到控制台上有加载你自己虚拟目录的信息,你的站点要安装规范建立(WEB-INF什么的就不唠叨了)
在manager中,可以reload自己的虚拟目录
数据源连接池,我擦的,这个可是郁闷死我了,就因为粗心大意,配置了好久,各位汲取我的教训吧
我是按照tomcat里的doc帮助文档里面的方式配的,文档所在目录:http://localhost:8080/docs/jndi-datasource-examples-howto.html
分别配置了 自己站点下的 context.xml(META-INF目录下) 和 自己站点下的 web.xml (WEB-INF目录下)以及在tomcat 目录中的localhost里的context.xml,就是最上面那个
<Context> <Resource name="jdbc/lhdb" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="1000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/lhdb" /> </Context>
<resource-ref> <description>MySql Conneciton</description> <res-ref-name>jdbc/lhdb</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
这样就配置好了,按照基本流程配置不会出什么问题,一般会抛出cannot create jdbc driver 这个你把数据库驱动jar包扔到tomcat里的lib中和自己站点里的lib中
如果要是出现cannot create PoolableConnectionFactory(Communications link failure 建议你检查一下数据源配置的url 我纠结了一天就是因为我把local写成了locol
使用:
import java.sql.*; import javax.sql.*; import javax.naming.*; public class ConnDB{ private Connection ct = null; public Connection getConn(){ try{ Context initCtx = new InitialContext(); Object obj = initCtx.lookup("java:comp/env/jdbc/lhdb"); DataSource ds = (DataSource)obj; ct = ds.getConnection(); }catch(Exception e){ e.printStackTrace(); } return ct; }
ok