1.在项目WEB-INF/web.xml中增加如下代码:
<resource-ref>
<description>Admin connect to DB</description>
<res-ref-name>jndiconn</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
res-ref-name很重要,与context.xml中的name要一致。
2.tomcat的context.xml中增加配置如下:
<Resource name="jndiconn" auth="Container" type="javax.sql.DataSource"
maxActive="100" minIdle="10" maxWait="10000" initialSize="10"
username="test" password="test" driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@127.0.0.1:1521:orcl" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true" testOnBorrow="true" testOnReturn="false"
validationQuery="SELECT 1 from dual" validationInterval="30000"
timeBetweenEvictionRunsMillis="30000" removeAbandonedTimeout="60"
removeAbandoned="true" logAbandoned="true" minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" />
3.将oracle驱动程序加入到tomcat的lib中
D:\apache-tomcat-7.0.57-windows-x64\apache-tomcat-7.0.57\lib
4.java连接数据源代码:
public static Connection getConnection() {
Connection conn = null;
try {
// jdbc
// InputStream inputStream = CommonUtils.class
// .getResourceAsStream("databaseConfig.properties");
// Properties p = new Properties();
// p.load(inputStream);
// String driver = p.getProperty("driverName");
// String url = p.getProperty("databaseUrl");
// String userName = p.getProperty("userName");
// String passWord = p.getProperty("passWord");
// Class.forName(driver);
// conn = DriverManager.getConnection(url,userName,passWord);
// conn.setAutoCommit(false);
// jndi
Context initContext = new InitialContext();
DataSource dataSource = (DataSource) initContext
.lookup("java:comp/env/jndiconn");
return dataSource.getConnection();
} catch (Exception e) {
System.out.println("建立数据库连接错误!" + e.toString());
e.printStackTrace();
}
return conn;
}
5.完成jndi连接oracle数据库。