tomcat JNDI 的配置

JNDI Tomcat 启动错误
Scene:
在 Tomcat 测试 JNDI。(配置context.xml和web.xml的JDBC资源参数以供web应用连接至mysql数据库)
错误信息:
Creation of the naming context failed:  javax.naming.OperationNotSupportedException: Context is read only

Solution:
? No solution yet


Tomcat MySQL JNDI 配置
Scene:
利用 JNDI 来为某个 App 配置数据源。(在 apache tomcat 提供的文档里面有提及"JNDI Datasource How-To")
好处是在该 App 的代码文件里面可以实用 JNDI 提供的接口来链接数据库,以后更改数据库产品的时候只需要一次性配置该 App 的配置文件就可以了。而不需要更改所有文件里面的代码。

Solution:
需要配置的文件有 context.xml 和 web.xml。当然(mysql的驱动可以放在web应用的 $root/WEB-INF/lib 下面,也可以放在 $tomcat/lib 下面)

context文件内容(其中的各项值的意义可以参考 tomcat 提供的文档):
在 context.xml 里面添加 <Context> 结点,在 <Context> 中定义 <Resource>。

 
[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <Context>  
  3.   <Resource name="jdbc/mysql"   
  4.     auth="Container"  
  5.     type="javax.sql.DataSource"  
  6.     driverClassName="com.mysql.jdbc.Driver"  
  7.     url="jdbc:mysql://localhost:3306/test"  
  8.     username="root"  
  9.     password="tsm;jd"  
  10.     removeAbandoned="true"  
  11.     removeAbandonedTimeout="120"  
  12.     maxWait="60"  
  13.     maxActive="20"  
  14.     maxIdle="10"  
  15.     />  
  16. </Context>  


web.xml文件需要添加的内容:
在 web.xml 里面定义 <resource-ref> 结点。
[html]  view plain  copy
  1.       
  2. <resource-ref>  
  3.   <description>the data source of mysql database, the application could use this resource to   
  4. connect to the database</description>  
  5.   <res-ref-name>mysql-ds</res-ref-name>  
  6.   <res-type>javax.sql.DataSource</res-type>  
  7.   <res-auth>Container</res-auth>  
  8.   <lookup-name>jdbc/test</lookup-name>  
  9.  </resource-ref>  
可以通过菜单(安装 JBoss 社区提供的 JBoss Studio 在 eclipse 里面)
 
调用:
[java]  view plain  copy
  1. import java.sql.Connection;  
  2. import javax.naming.Context;  
  3. import javax.naming.InitialContext;  
  4. import javax.naming.NamingException;  
  5. import javax.sql.DataSource;  
  6.   
  7. private static Connection CONNECTION;  
  8. static  
  9. {  
  10.     try  
  11.     {  
  12.         Context ctx = new InitialContext();  
  13.         Object datasourceRef = ctx.lookup("java:comp/env/jdbc/mysql");  
  14.         DataSource ds = (DataSource)datasourceRef;  
  15.         CONNECTION = ds.getConnection();  
  16.     }  
  17.     catch (NamingException e)  
  18.     {  
  19.         e.printStackTrace();  
  20.     }  
  21.     catch (SQLException e)  
  22.     {  
  23.         e.printStackTrace();  
  24.     }  
  25. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值