数据库是oracl10g的版本 tomcat 6
1.项目中web/WEB-INF/lib 有驱动包 ojdbc14
2.在tomcat中 server.xml文件
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
<Resource name="jdbc/jspdev" auth="Container"
type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@192.168.1.188:1521:orcl"
username="myf" password="myf" maxActive="20" maxIdle="10"
maxWait="-1"/>
</GlobalNamingResources>
3 。在server.xml <Host>下 把jndi资源引用到某一项目的context中去
<Context path="" docBase="E:/tomcat/apache-tomcat-6.0.20/webapps/myf" debug="0" reloadable="true" crossContext="true">
<ResourceLink name= "jdbc/jspdev" global= "jdbc/jspdev" type= "javax.sql.DataSourcer"/>
</Context>
4.项目中 web.xml 加入
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/jspdev</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
5.测试代码
public class ConnectionManager {
public static Connection getConnection() throws DaoException {
/*
Connection conn = null;
try {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.188:1521:orcl", "myf", "myf");
} catch (SQLException e) {
throw new DaoException("can not get database connection", e);
}
return conn;*/
Connection conn = null;
try {
conn = MyfDataSource.getDataSource().getConnection();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}
public class MyfDataSource{
private static DataSource ds = null;
private MyfDataSource(){
}
public static synchronized DataSource getDataSource(){
if(ds==null){
InitialContext initContext;
try {
initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
ds = (DataSource)envContext.lookup("jdbc/jspdev");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ds;
}
}
参考http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html#Oracle_8i,_9i_&_10g