终于有机会写一些比较基础的代码了,终于有机会在tomcat上配置jndi数据源了,但是这是一个费时间的过程。这里把这个过程记录如下。
目的:tomcat提供数据源,java代码中通过jdbc获取jndi,操作数据库。
步骤:
1、讲数据库的驱动jar放到tomcat的lib目录下,%TOMCAT_HOME%\lib
2、修改%TOMCAT_HOME%\conf目录下配置文件server.xml,增加如下内容:
<Context docBase="/securityProxyWeb" path="/securityProxyWeb" reloadable="true" debug="5" crossContext="true">
<Resource name="jdbc/exoa" auth="Container" type="javax.sql.DataSource" maxIdle="10" initialSize="10" maxWait="10000" maxActive="20"
driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@127.0.0.1:1521:exoa" username="exoa" password="exoaexoa" />
</Context>
注意上面的代码放在Host节点下面,如果读者要用的话,请修改具体的参数,username\password\url
3、web功能里面要使用tomcat的数据源,需在web.xml里面增加引用:
<resource-ref id="ResourceRef_1401952150839">
<res-ref-name>jdbc/exoa</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
4、获取Connection的代码如下:
/**
* 获取数据库连接
*
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
Context context = null;
DataSource dataSource = null;
try {
context = new InitialContext();
try{
//TOMCAT JDK1.6
dataSource = (DataSource) context.lookup("java:comp/env/jdbc/exoa");
}catch(Exception E){
E.printStackTrace();
}
if(dataSource == null){
//WAS JDK1.4
dataSource = (DataSource) context.lookup("jdbc/exoa");
}
if (dataSource == null) {
System.err.println("打开数据库连接出错!!!");
return null;
}
return dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}