JNDI配置数据源

java代码中使用配置的资源:

1 Context ctx;
2 try {
3 ctx = new InitialContext();
4 ds=(DataSource)ctx.lookup("java:comp/env/jdbc/test");
5 
6 } catch (NamingException e) {
7 // TODO Auto-generated catch block
8 e.printStackTrace();
9 }
View Code

在应用的web.xml中注册该资源

1 <resource-ref>
2       <description>DB Connection</description>
3       <res-ref-name>jdbc/test</res-ref-name>
4       <res-type>javax.sql.DataSource</res-type>
5       <res-auth>Container</res-auth>
6   </resource-ref>
View Code

接下来就是配置具体参数:

  1.为单个应用配置jndi,在META-INF文件夹中加入文件context.xml

  

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <Context  >
 3   <Resource 
 4                  name="jdbc/test"
 5                type="javax.sql.DataSource"
 6                maxActive="100"
 7                maxIdle="30"
 8                maxWait="10000"
 9                username="charlie"
10                password="asdf"
11                driverClassName="oracle.jdbc.driver.OracleDriver"
12                url="jdbc:oracle:thin:@192.168.1.111:1521:orcl"/>
13 
14 </Context>
View Code

  效果同在tomcat下conf文件夹下localhost下新建:应用名.xml,内容和上面一致;(通过实验发现,tomcat会根据context.xml自动生成应用名.xml)

 

 

   2.配置全局jndi.,在tomcat_home/conf/server.xml的host节点中加入:

 1 <Context path="" docBase="/" 
 2                     reloadable="true" >
 3 
 4         <Resource 
 5                  name="jdbc/test"
 6                type="javax.sql.DataSource"
 7                maxActive="100"
 8                maxIdle="30"
 9                maxWait="10000"
10                username="charlie"
11                password="asdf"
12                driverClassName="oracle.jdbc.driver.OracleDriver"
13                url="jdbc:oracle:thin:@192.168.1.111:1521:orcl"/>
14 
15    
16 
17 </Context>
View Code

并且在每个应用的META-INF加入context.xml,加入对全局jndi的映射后该webapp既可以使用全局jndi

1 <Context docBase="/test" path="test" reloadable="false">
2     <ResourceLink name="test " global="test " type="javax.sql.DataSource"/>
3 </Context>
View Code

 

posted on 2013-09-22 20:39  a_badegg  阅读(323)  评论(0编辑  收藏  举报

导航