tomcat JNDI 的配置

来源:互联网 发布:linux local 编辑:程序博客网 时间:2024/05/17 08:41
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
(link:http://stackoverflow.com/questions/15340218/what-could-cause-javax-naming-operationnotsupportedexception-when-tomcat-start)


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
原创粉丝点击