在网上看到很多的在tomcat的conf目录中配置server.xml来配置数据源。其实在JavaWeb项目中不用改服务器中的配置,而META-INF目录中增加一个context.xml的配置即可。
参考配置如下:
<Context path="/FusionChartLearn" docBase="FusionChartLearn"
debug="5" reloadable="true" crossContext="true">
<Logger className="org.apache.catalina.logger.FileLogger"
prefix="localhost_DBTest_log." suffix=".txt"
timestamp="true"/>
<Resource name="jdbc/FactoryDB"
type="javax.sql.DataSource"
auth="Container"
url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"
username="scott"
password="scott"
driverClassName="oracle.jdbc.driver.OracleDriver"
validationQuery="select sysdate from dual"
maxWait="5000"
maxActive="4"
maxIdle="2"
removeAbandoned="true"
removeAbandonedTimeout="30"
logAbandoned="false" />
</Context>
配置方法跟修改server.xml文件方式类似。
使用方法:
Connection oConn = null;
oConn = null;
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/FactoryDB");
oConn = ds.getConnection();
} catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}