java 使用tomcat的JNDI数据源

终于有机会写一些比较基础的代码了,终于有机会在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;
		}
	}

 

转载于:https://my.oschina.net/psuyun/blog/273873

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值